KatInterview

Detect Merge Point of Two Rho-Shaped Index Chains

Linked ListsAuto-graded · 16 test cases
HardAuto-gradedLinked Listslinked listscycle detectiontwo pointers

Last updated

Tests mastery of Floyd's cycle-detection algorithm and two-pointer merge-point finding applied to implicit linked lists encoded as index arrays.

Detect Merge Point of Two Rho-Shaped Index Chains

You are given two integer arrays, next_a and next_b, each of length n. They encode two implicit singly-linked lists over the same node universe {0, 1, …, n-1}:

  • Following list A from node i takes you to node next_a[i].
  • Following list B from node i takes you to node next_b[i].

Both lists start at node 0 and are rho-shaped (ρ): each has a (possibly empty) tail leading into exactly one cycle. Because both lists share the same node universe, their paths must eventually overlap — there is guaranteed to be at least one node that appears in both the reachable sequence of list A and the reachable sequence of list B.

Your task: find the first node (smallest index) that is reachable from node 0 in both list A and list B.

"Reachable from node 0" means the node appears in the infinite sequence 0, next[0], next[next[0]], … — including the cycle portion that is visited repeatedly.

Definitions

  • Reachable set of A: all nodes that appear in 0, next_a[0], next_a[next_a[0]], … (up to and including the first repeated node, after which the cycle repeats).
  • Reachable set of B: analogously for next_b.
  • The answer is the node with the smallest index that belongs to both reachable sets.

Constraints

  • 1 ≤ n ≤ 2000
  • next_a and next_b are each arrays of length n.
  • 0 ≤ next_a[i] < n and 0 ≤ next_b[i] < n for all i.
  • Both chains are rho-shaped: starting from node 0, following either array will eventually cycle.
  • The intersection of the two reachable sets is non-empty (a solution always exists).
  • You must return exactly one integer — the smallest-indexed node in the intersection.

Examples

Example 1

Input: find_merge_node([1, 2, 3, 1], [2, 3, 1, 2])

Output: 0

Example 2

Input: find_merge_node([1, 2, 0, 4, 3], [3, 4, 1, 4, 3])

Output: 0

Example 3

Input: find_merge_node([1, 2, 3, 4, 2], [4, 0, 3, 4, 2])

Output: 0

Hints

Hint 1

Use Floyd's tortoise-and-hare algorithm independently on each array to identify all nodes in each reachable set without allocating O(n) visited sets — or, since n ≤ 2000, think about what a simpler O(n) traversal with a boolean array gives you.

Hint 2

To collect the full reachable set of one chain: walk from node 0, recording each node you visit; stop as soon as you revisit a node (you have completed exactly one pass through the tail + one full cycle traversal).

Hint 3

Once you have both reachable sets as boolean arrays of length n, the answer is simply the minimum index i where both flags are True.