Intersection of Two Linked Lists

Find the node where two singly-linked lists merge, in O(1) extra space, via the pointer-swap technique.

Easy
Time O(n + m) Space O(1)
LeetCode
3 min read
two-pointers linked-list

Problem#

Two singly-linked lists may merge at some node and share their suffix. Return that merge node, or nullptr if they don’t intersect.

Examples#

  • Two lists that share a tail starting at value 8 → return that node.

Constraints#

  • Lists may be of different lengths; no cycles.

Hints#

Hint 1
If lengths matched, walking in lockstep would find the merge. Lengths don’t match — pad each pointer with the other list.

Approach#

Two pointers a, b start at the two heads. At each step, advance one node; when a pointer reaches null, restart it at the other head. Both pointers traverse exactly lenA + lenB nodes and meet at the merge (or simultaneously hit null if disjoint).

Solution#

Intersection of Two Linked Lists
class Solution {
public:
ListNode* getIntersectionNode(ListNode* headA, ListNode* headB) {
ListNode *a = headA, *b = headB;
while (a != b) {
a = a ? a->next : headB;
b = b ? b->next : headA;
}
return a;
}
};

Editorial#

The pointer-swap aligns the effective starting positions: from a’s perspective it walks lenA + lenB nodes total before meeting b, which walks the same. They land on the intersection — or, if no intersection exists, both reach null simultaneously and the loop exits cleanly.

Complexity#

  • Time: O(n + m).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.