Intersection of Two Linked Lists - Problem

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.

For example, the following two linked lists begin to intersect at node c1:

The test cases are generated such that there are no cycles anywhere in the entire linked structure.

Note: The linked lists must retain their original structure after the function returns.

Input & Output

Example 1 — Lists Intersect
$ Input: listA = [4,1,8,4,5], listB = [5,6,1,8,4,5]
Output: [8,4,5]
💡 Note: The intersection starts at node with value 8. Both lists share the same tail: 8→4→5
Example 2 — No Intersection
$ Input: listA = [2,6,4], listB = [1,5]
Output: null
💡 Note: The two linked lists have no common nodes, so return null
Example 3 — Single Node Intersection
$ Input: listA = [3], listB = [2,3]
Output: [3]
💡 Note: Lists intersect at the single node with value 3

Constraints

  • The number of nodes in listA is m
  • The number of nodes in listB is n
  • 1 ≤ m, n ≤ 3 × 104
  • 1 ≤ Node.val ≤ 105

Visualization

Tap to expand
INPUTTwo Linked ListsList A:418List B:568Green nodes are samereference (intersection)ALGORITHMTwo Pointers Approach1Start both pointers at heads2Move pointers forward together3When pointer reaches end,jump to other list head4Pointers meet at intersectionKey: Both travel same distance(length A + length B)RESULTIntersection FoundOutput:[8, 4, 5]List fromintersectionTime: O(m+n)Space: O(1)Key Insight:Two pointers switching lists will always meet at intersection or both become nullTutorialsPoint - Intersection of Two Linked Lists | Two Pointers Approach
Asked in
Amazon 65 Microsoft 45 Google 38 Facebook 32
95.0K Views
High Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen