Two singly linked lists start at headA and headB. From some node on, the two lists may share the very same nodes, so they form a Y shape. Return that first shared node, or null if the lists never join.
Sharing means the same node in memory. Two different nodes that happen to hold the same value do not count. There are no cycles, and both lists must look the same after your function returns.
Example 1
Input: listA = [3, 7, 5, 9], listB = [6, 5, 9],
skipA = 2, skipB = 1
Output: the node with value 5
Why: A[2] and B[1] are the same node; 9 after it is shared too2 more examples and the constraints
Example 2
Input: listA = [2, 4, 2, 4], listB = [4, 2, 4],
skipA = 2, skipB = 1
Output: the node A[2], value 2
Why: A[0] also holds 2, but it is a different nodeExample 3
Input: listA = [1, 3, 5], listB = [2, 4],
skipA = 3, skipB = 2
Output: null
Why: the lists end separatelyConstraints
- 1 ≤ length of A, length of B ≤ 30,000
- 1 ≤ node value ≤ 100,000
- The input says how many nodes of each list come before the shared part (skipA, skipB); your function only gets the two heads
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Hash set of nodesO(m + n)
- Two pointers that switch listsO(m + n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 30,000 nodes each | Verdict |
|---|---|---|---|
| Hash set of nodes | O(m + n) | Passes; O(m) memory | |
| Two pointers that switch lists | O(m + n) | Best; no extra memory |
m and n = lengths of A and B. Both are linear; the set also pays for hashing.
Edge cases to test
- No intersection. Both pointers hit null after m + n moves and null is returned.
- Same head. If A and B are the same list, the loop never runs and the head is returned.
- Equal values, different nodes. Compare node references, never
val. - Join at the last node. The shared part can be a single tail node.
- One list inside the other. B can start at a node of A; then that node is the answer.
Common mistakes
- Comparing
a.val == b.valinstead of the nodes themselves. - Switching a pointer to the other head without spending a move on null, which loops forever when the lists do not meet.
- Changing the lists (for example linking the tail to a head) and not restoring them.
How to talk through it
- 1Clarify. Do we compare nodes or values? Can there be cycles? May I change the lists?
- 2Give the set. Store A's nodes, scan B; O(m + n) time and O(m) memory.
- 3Explain the lengths. x + z + y equals y + z + x, so walking both lists in opposite order lines the pointers up.
- 4Code the switch. Move each pointer, and send it to the other head when it is null.
- 5Test out loud. Run no intersection, the same head, and equal values on different nodes.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?