KatInterview

Find All Rho-Shape Cycle Tails in a Functional Graph

Linked ListsAuto-graded · 17 test cases
HardAuto-gradedLinked Listslinked listscycle detectiongraphs

Last 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 i is on a cycle if and only if repeatedly following next from i eventually returns to i.
  • 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 ≤ 2000
  • 0 ≤ next[i] < n for all i
  • next may 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).