Detect Merge Point of Two Rho-Shaped Index Chains
Linked ListsAuto-graded · 16 test casesLast 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
itakes you to nodenext_a[i]. - Following list B from node
itakes you to nodenext_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 ≤ 2000next_aandnext_bare each arrays of lengthn.0 ≤ next_a[i] < nand0 ≤ next_b[i] < nfor alli.- 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.
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key Insight
Each array encodes a rho-shaped (ρ) traversal: starting from node 0 and following the next pointers, you walk a tail of distinct nodes and then enter a cycle you loop around forever. The complete reachable set is finite: it is exactly the nodes you visit before (and including) the first time you revisit any node.
Algorithm
- Collect reachable set of A: Walk
0 → next_a[0] → next_a[next_a[0]] → …, settingvisited_a[node] = True, until you reach a node already marked. At that point every reachable node has been marked exactly once. - Collect reachable set of B: Same procedure with
next_b. - Find the answer: Scan indices
0, 1, …, n-1in order and return the firstiwhere bothvisited_a[i]andvisited_b[i]areTrue.
Why it is correct
- The walk terminates because the chain is rho-shaped: once a node is revisited the future path is a strict repeat, so no new nodes are ever added.
- Every node in the reachable set is visited before the termination condition triggers (the repeated node is already marked when we try to mark it a second time).
- Scanning in ascending index order and returning the first common node guarantees the minimum-index intersection element.
Complexity
| Time | Space | |
|---|---|---|
| Reachable set construction (×2) | O(n) each | O(n) each |
| Linear scan for minimum | O(n) | O(1) |
| Total | O(n) | O(n) |
Both time and space are linear in n, well within the n ≤ 2000 constraint.
Why Floyd's algorithm is relevant (but not required here)
Floyd's tortoise-and-hare algorithm can detect that a cycle exists and locate the cycle entry point in O(1) extra space. For this problem, since n ≤ 2000, the O(n) boolean-array approach is cleaner and still efficient. A full Floyd-based solution would:
- Use tortoise/hare to find a node inside the cycle of each chain (O(1) space).
- Determine cycle length and entry point.
- Enumerate the full reachable set without a visited array.
The boolean-array solution is equivalent and easier to verify correct.
from typing import List
def find_merge_node(next_a: List[int], next_b: List[int]) -> int:
n = len(next_a)
def reachable_set(nxt: List[int]) -> List[bool]:
"""Walk from node 0, mark every node visited before the first repeat."""
visited = [False] * n
cur = 0
while not visited[cur]:
visited[cur] = True
cur = nxt[cur]
return visited
reach_a = reachable_set(next_a)
reach_b = reachable_set(next_b)
for i in range(n):
if reach_a[i] and reach_b[i]:
return i
# Guaranteed by problem constraints never to reach here.
raise ValueError("No common node found")