Intersection of Two Linked Lists
Easy
Linked ListTwo Pointers
Problem
Two singly linked lists eventually merge. Return the node where they first intersect (by reference), or null.
Example 1
Input: A=[4,1,8,4,5], B=[5,6,1,8,4,5]
Output: 8
Constraints
- 1 ≤ each list length ≤ 10⁴
Approach — Two Pointers
This is a Two Pointers problem. The idea: walk two indices through the data together (or toward each other), turning an O(n²) pair search into one linear pass. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.
Complexity: O(n) time, O(1) extra space.
Solution code
Python
class Solution:
def getIntersectionNode(self, headA, headB):
a, b = headA, headB
while a is not b:
a = a.next if a else headB
b = b.next if b else headA
return a
Java
class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode a = headA, b = headB;
while (a != b) {
a = a == null ? headB : a.next;
b = b == null ? headA : b.next;
}
return a;
}
}
Practice it
Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.
Solve Intersection of Two Linked Lists interactively → ← All solutions