Find the node where two lists join: walk each list, switch to the other head at the end, and both runners meet at the join.
▼The problem
LeetCode 160 (Easy). Given the heads of two singly linked lists, return the node where they intersect (the same node object, not just an equal value), or null if they never join.
Examples (LeetCode's): listA = [4,1,8,4,5], listB = [5,6,1,8,4,5] meet at the node with value 8 (both lists hold a 1, but those are two different nodes); listA = [2,6,4], listB = [1,5] → null.
def get_intersection_node(head_a, head_b):
a, b = head_a, head_b
while a is not b:
a = a.next if a else head_b
b = b.next if b else head_a
return aTRY IT ON LEETCODE ▶The solution
def get_intersection_node(head_a, head_b):
a, b = head_a, head_b
while a is not b:
a = a.next if a else head_b
b = b.next if b else head_a
return aTranscript
Intersection of Two Linked Lists. You get the heads of two linked lists that may merge into one shared tail. Return the first node they share: the same node, not just an equal value. If they never join, return null.
Here, list A is four, one, eight, four, five, and list B is five, six, one, eight, four, five. Both hold a one, but those are two different nodes. The first node they truly share is the eight. In a second example, the lists never join, so the answer is null.
The slow way: for each node of A, scan all of B. With m and n nodes, that's up to m times n checks. A hash set of A's nodes is faster, but it costs m extra space.
Why not just step two pointers together? A starts two nodes before the join, but B starts three. B is always one step behind, so they keep missing each other.
The trick: switch heads. Pointer A walks list A, and when it falls off the end, it jumps to the head of B. Pointer B does the reverse. Say A has a nodes of its own, B has b, and they share c. Each pointer walks a plus c plus b before the join, the same distance, so they arrive together.
In code, start a pointer at each head. While they're different nodes, step both forward, and send one that falls off the end to the other head. When they meet, return that node.
On the example, pointer A passes four, one, eight, four, five, then switches. Pointer B passes all six of its nodes, then switches. After nine steps, both land on the eight. On the second example, both reach null on the same step, and the answer is null.
Each pointer visits at most m plus n nodes, so the time is O of m plus n. We keep only two pointers, so the space is O of one.
Walk your list, switch heads, meet up. That's Intersection of Two Linked Lists.