Skip to content

visual walkthrough

Intersection of Two Linked Lists

EasyTwo Pointers (Length Equalising)Reported at: AmazonMicrosoftMeta+5

Switching heads equalises path lengths, an elegant trick.

Solve on LeetCode

The idea

Two lists that share a tail meet at one node and run together after it. The trouble is they may reach it after different numbers of steps.

If each pointer walks its own list and then the other one, both walk the same total distance, so they arrive at the shared node (or at null) at the same moment.

Complexity

approachtimespace
Remember A's nodesO(n + m)O(n)
Switch headsO(n + m)O(1)

More walkthroughs