Start learning free

LESSON 439 OF 679 · LINKED LISTS

Intersection of Two Linked Lists

Practice O(n)

You get headA and headB, the heads of two singly linked lists. Return the first node that both lists share, or None if they never join.

Two lists join at a node when both go on through the very same nodes, to the end.

In this picture, A has two nodes of its own and B has three. Then both go through c1, c2 and c3. The answer is c1:

A B a1 a2 b1 b2 b3 c1 c2 c3

What matters is the node itself, not its value. Two different nodes can hold the same number.

Neither list has a loop. Both lists must stay exactly as they were after your function returns.

The examples write out each list in full. They also give shared, the number of nodes at the end that are in both lists. It is 0 when the lists don't join.

The tests use shared to build the lists. Your function gets only headA and headB.

 

Example 1:

A B 3 5 5 9 4

Input: listA = [3,5,9,4], listB = [5,9,4], shared = 2
Output: the node with value 9
Explanation: The green nodes, 9 -> 4, are in both lists.
Each list also has a 5, but they are two different nodes.
So the first shared node is the 9.

Example 2:

A B 8 2 6 1 7 3

Input: listA = [8,3], listB = [2,6,1,7,3], shared = 1
Output: the node with value 3
Explanation: Only the last node, the green 3, is shared.
A has 1 node before it, and B has 4.

Example 3:

A B 6 2 8 4 1

Input: listA = [6,2,8], listB = [4,1], shared = 0
Output: None
Explanation: No node is in both lists.

 

Constraints:

  • Each list has 1 to 30,000 nodes.
  • Each list has at least one node of its own, before the shared part.
  • Each value is from 1 to 100,000.

 

Follow up: Can you find the node in O(m + n) time and O(1) extra memory? Here m and n are the two lengths.
STEP 1 OF 20
    Ctrl + Enter to check