Intersection of Two Linked Lists
LeetCode 160 · Easy · solution, intuition & step-by-step walkthrough
Switch heads at the end; equal path lengths make them meet.
This is how I solved Intersection of Two Linked Lists (LeetCode 160), an easy problem from the Intersection pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Walk pointer A through list A then list B, and pointer B through list B then list A. Both travel the same total distance, so they line up and meet at the intersection — or both reach the end together if there isn't one.
Approach
- 1
p1 = headA, p2 = headB.
- 2
Step both; when one reaches the end, jump to the other list's head.
- 3
Stop when they're the same node (or both None).
How I solved it
Two-pointer head switchingPythonO(m+n) time · O(1) space
class Solution:
def getIntersectionNode(self, headA, headB):
p1 = headA
p2 = headB
while p1 != p2:
p1 = headB if p1 is None else p1.next
p2 = headA if p2 is None else p2.next
return p1Intersection of Two Linked Lists — FAQ
What is the intuition behind Intersection of Two Linked Lists?
Walk pointer A through list A then list B, and pointer B through list B then list A. Both travel the same total distance, so they line up and meet at the intersection — or both reach the end together if there isn't one.
How do you solve Intersection of Two Linked Lists (LeetCode 160)?
1. p1 = headA, p2 = headB. 2. Step both; when one reaches the end, jump to the other list's head. 3. Stop when they're the same node (or both None).
What is the time and space complexity of Intersection of Two Linked Lists?
Time: O(m + n). Space: O(1). (Accepted approach: Two-pointer head switching.)
What are common mistakes in Intersection of Two Linked Lists?
Compare node identity, not values.