Find All Rho-Shape Cycle Tails in a Functional Graph
Linked ListsAuto-graded · 17 test casesLast updated
Tests cycle detection via Floyd's / index-chasing on a pure-array functional graph, requiring candidates to identify every node's "tail length" before it enters a cycle.
Find All Rho-Shape Cycle Tails in a Functional Graph
A functional graph is defined by an array next of length n, where next[i] is the index of the node that node i points to (0 ≤ next[i] < n). Because every node has exactly one outgoing edge, each connected component looks like a rho (ρ): a "tail" of nodes leading into a cycle.
The tail length of node i is the number of steps you must follow from node i before you first land on a node that is part of a cycle. Nodes already on a cycle have a tail length of 0.
Given next, return a list result of length n where result[i] is the tail length of node i.
Details
- A node
iis on a cycle if and only if repeatedly followingnextfromieventually returns toi. - For a node not on a cycle, its tail length equals the number of edges traversed until a cycle node is reached (that cycle node itself is not counted as a step).
- The answer is unique; no tie-breaking is needed.
Constraints
1 ≤ n ≤ 20000 ≤ next[i] < nfor allinextmay encode multiple independent components, each with its own cycle.- Self-loops (
next[i] == i) are valid and form a cycle of length 1.
Examples
Example 1
Input: cycle_tail_lengths([1, 2, 3, 1])
Output: [1, 0, 0, 0]
Example 2
Input: cycle_tail_lengths([1, 0, 3, 2])
Output: [0, 0, 0, 0]
Example 3
Input: cycle_tail_lengths([0])
Output: [0]
Hints
Hint 1
First, identify which nodes lie on a cycle. One approach: for each starting node, follow pointers until you either revisit a node you have seen on this walk or land on a node already classified. Floyd's two-pointer trick can confirm cycle membership for a single component, but you need to handle multiple independent components.
Hint 2
Once every cycle node is marked, a second pass can compute tail lengths: any node whose `next` pointer leads to a cycle node has tail length 1; a node pointing to that node has tail length 2, and so on. This is essentially computing depths in a forest whose roots are the cycle nodes.
Hint 3
To avoid re-traversing long tails repeatedly, use memoisation (or iterative path-compression): walk from an unresolved node, collect the path, then fill in tail lengths backwards once you hit a node whose tail length is already known (cycle nodes count as known with value 0).
Worked solution
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key Insight
Every node in a functional graph eventually reaches a cycle (since n is finite and each node has exactly one successor). The "tail length" is simply how many steps away from the cycle a node sits.
Algorithm
We iterate over every node as a potential starting point, skipping nodes already resolved. For each unresolved start we trace a path forward, recording each node's position in the current walk:
-
Hit an already-resolved node: every node on the current path lies on a tail leading toward that resolved node. We back-fill distances: the node immediately before the resolved node gets
result[resolved] + 1, the one before that getsresult[resolved] + 2, etc. -
Revisit a node seen on the current path: we have found a cycle. All nodes from that revisited node to the end of the collected path are on the cycle → tail length
0. All nodes before that index are on the tail leading into the cycle → fill in1, 2, 3, …in reverse.
Because each node is resolved at most once, the total work across all starting points is O(n) time and O(n) space (for the result array and per-walk bookkeeping).
Correctness
- A node is on a cycle iff the path from it returns to itself before hitting any previously resolved node. The
visited_in_pathdictionary captures exactly that. - Back-filling in reverse gives the correct monotonically increasing distance from the cycle.
- Multiple independent components are handled naturally because the outer
for start in range(n)loop covers every node.
Complexity
- Time: O(n) — each node is appended to a path and resolved exactly once.
- Space: O(n) —
resultarray plus at most O(n) for one walk'spathandvisited_in_path.
Reference Solution
from typing import List
def cycle_tail_lengths(next: List[int]) -> List[int]:
n = len(next)
result = [-1] * n # -1 = unresolved
for start in range(n):
if result[start] != -1:
continue
path = []
visited_in_path = {} # node -> index in path
node = start
while True:
if result[node] != -1:
# Back-fill: nodes at the END of path are closest to node
dist = result[node]
for p in reversed(path):
dist += 1
result[p] = dist
break
if node in visited_in_path:
# Cycle detected
cycle_start_idx = visited_in_path[node]
# Mark cycle nodes
for p in path[cycle_start_idx:]:
result[p] = 0
# Mark tail nodes
dist = 0
for p in reversed(path[:cycle_start_idx]):
dist += 1
result[p] = dist
break
visited_in_path[node] = len(path)
path.append(node)
node = next[node]
return result