Skip to problem
←

Intersection of Two Linked Lists

Easy 0 attempts

You're given the heads of two singly linked lists, headA and headB, which may merge into a shared tail at some point. Find and return the exact node where they come together, or null if they never do. Neither list may be modified in the process — both must look the same after your function returns — and you're guaranteed neither list loops back on itself anywhere.

Function contract

listFixture = [prefixA, prefixB, sharedTail]. The runner builds separate prefix nodes and one shared tail, then passes headA and headB. An empty sharedTail means no intersection.

Output: Return the first node shared by both lists, or null. Return the node itself, not its value or a copy. The runner verifies identity and unchanged input lists, then displays its value.

Example 1

Input
listFixture = [[4,1],[5,6,1],[8,4,5]]
Output
8

Example 2

Input
listFixture = [[1],[2],[]]
Output
null
Visual Aid
Two prefixes, one shared tail
AB41561845

The two prefix nodes valued 1 are different objects. The intersection is the shared node valued 8; every node after it is shared too.

Constraints
  • 0 <= length of either list <= 3 * 10^4
  • 1 <= node.val <= 10^5
  • Lists are acyclic; intersection means shared node identity, not equal values.
Topics

Approach: Two Pointers

Use two pointers, one starting at each head. When a pointer reaches the end of its list, redirect it to the head of the other list. Both pointers travel the same total distance, so they will meet at the intersection node, or both reach null if there is no intersection.

javascript
function intersectionOfTwoLinkedLists(headA, headB) {
  let a = headA, b = headB;
  while (a !== b) {
    a = a ? a.next : headB;
    b = b ? b.next : headA;
  }
  return a;
}

Time Complexity: O(m + n)

Space Complexity: O(1)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript