Skip to content

ORIGINAL CODING QUESTION

Where two referral chains meet

Two referral chains live in one pool of n nodes, where each node stores only the index of its next node (-1 ends a chain). Chain A starts at headA and chain B starts at headB. Once the chains reach a common node they share every node after it. Return the index of the first node that belongs to both chains, or -1 if they never meet. If both heads are the same node, that node is the answer.

Open practice workspace

Original exercise · medium. Editorial role relevance does not imply a company has asked this question.

Input and output

n headA headB, then n next indices for nodes 0 to n-1. Print a node index or -1.

Constraints

1 ≤ n ≤ 200; heads in [0, n); each next is -1 or an index in [0, n); neither chain contains a loop; some nodes may belong to neither chain.

Example 1

Input

6 0 3
1 2 -1 4 2 -1

Output

2

A visits 0, 1, 2 and B visits 3, 4, 2, so they meet at node 2.

Example 2

Input

4 0 2
1 -1 3 -1

Output

-1

A is 0, 1 and B is 2, 3 with nothing in common.

Explain your approach

Explain your time and auxiliary space complexity. Which input makes your algorithm work hardest?

Private grading inputs, expected outputs and canonical reference implementations are withheld. Authored expected outputs were cross-checked with independent reference oracles; compiler/runtime behavior still needs a verified execution provider.

Hint 1

Marking every node of chain A, then walking chain B, works with extra memory.

Hint 2

The shared part is a common suffix, so the chains differ only before it.

Hint 3

Measure both lengths, advance the longer chain by the difference, then step both pointers together until they are equal (possibly both -1).

Practice this question

Save your work privately, explain decisions and return to your revision queue.

Open practice workspaceBrowse the question library →