Skip to content
BytePatterns

Where Two Chains Merge

EasyLinked Lists#two-pointers#list-traversal~15m

Problem

Two version histories are stored as singly linked lists that may join at a shared commit and run together from there to the end. Given the heads of both lists, return the first node they share, or None if they never meet. Shared means the same node object, not just an equal value. Do not change either list, and use only O(1) extra space. Each list has up to 30,000 nodes.

Examples

Input:  a = 4 -> 1 -> 8 -> 4 -> 5, b = 5 -> 6 -> 1 -> 8 -> 4 -> 5,
        both lists share the nodes 8 -> 4 -> 5
Output: the node holding 8
Why:    the 1 before it is a different node in each list, only the value matches
Input:  a = 2 -> 6 -> 4, b = 1 -> 5, no shared nodes
Output: None
Input:  a = 7, b = 7, where both heads are the same node
Output: the node holding 7
Why:    edge case, the lists share everything, so the answer is the head itself

Hints

0 / 3

Stuck on the idea rather than the code? Traversal and Search covers it.