2dbi

Intersection node of two linked lists

via2dbi

Problem

Given the heads of two singly linked lists that may merge at some node, return the node where they intersect, or null if they never do.

Example

A: a1 -> a2 -> c1 -> c2 -> c3
B:       b1 -> c1 -> c2 -> c3
intersection -> c1

Constraints

  • The lists may or may not intersect
  • Aim for O(m + n) time and O(1) space

Approach

Two-pointer walk: advance each pointer one node at a time, switching to the other list's head on reaching the end. The pointers meet at the intersection node, or at null if there is none.

Add a follow-up question they asked
Handle lists that may contain cycles
Why does the pointer-switch align?
asked …
LeaderboardSalary
Language
Account