AlgoInsight

DSA problem

Intersection of Two Linked Lists

EasyLinked ListPattern: Linked Listtop150AmazonMicrosoftBloombergAppleMeta

Given the heads of two singly linked lists headA and headB, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null.

The intersection is defined by reference, not by value: two lists intersect when they share the exact same node object from some point onward. After the intersection point, the two lists share every subsequent node. The structure of each list must remain unchanged after your function returns, and you may assume there are no cycles anywhere in the structure.

A naive approach would compare every node in list A against every node in list B, costing O(m * n) time. A better idea uses a hash set: walk list A storing each node reference, then walk list B and return the first node already in the set, taking O(m + n) time but O(m) extra space.

The optimal trick uses two pointers and exploits a clean algebraic identity. Let pointer pA traverse A then B, and pB traverse B then A. Each pointer travels exactly lenA + lenB nodes before reaching the end, so after at most that many steps they either meet at the intersection node or both reach null simultaneously. This switching of tracks neutralizes the length difference between the lists, giving an O(m + n) time, O(1) space solution.

Examples

Example 1
Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3
Output: Intersected at '8'
Explanation: The intersection node has value 8. From list A it is the 3rd node, and from list B it is the 4th node; both references point to the same object.
Example 2
Input: intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
Output: Intersected at '2'
Explanation: The two lists share the tail starting at the node with value 2, so that node is returned.
Example 3
Input: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2
Output: No intersection
Explanation: The lists do not share any node, so the function returns null.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

linked-listtwo-pointershash-table

Browse all DSA problems