Skip to content

ORIGINAL CODING QUESTION

Length of a referral loop

A referral tracker stores n nodes, each holding only the index of the next node, or -1 when there is none. Start at the head node and keep following next. Either the walk reaches -1, or it eventually repeats nodes forever around a loop. Return the number of nodes in that loop, or 0 if the walk ends. Nodes that cannot be reached from head are ignored.

Open practice workspace

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

Input and output

n head, then n next indices for nodes 0 to n-1 (-1 means no next node). Print the loop length or 0.

Constraints

1 ≤ n ≤ 200; 0 ≤ head < n; each next is -1 or an index in [0, n). A node may point to itself.

Example 1

Input

5 0
1 2 3 4 2

Output

3

The walk 0, 1, 2, 3, 4 returns to 2, so the loop is 2, 3, 4.

Example 2

Input

3 0
1 2 -1

Output

0

The walk ends after node 2.

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

Remembering visited nodes with their step numbers works but needs extra memory.

Hint 2

A pointer moving two steps per move meets a one-step pointer inside the loop if a loop exists.

Hint 3

After they meet, keep one pointer fixed and walk the other around until it returns, counting the steps.

Practice this question

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

Open practice workspaceBrowse the question library →