KatInterview

Find the Entry Point of a Rho-Shaped Index Chain

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

Last updated

Tests cycle detection on implicit linked lists encoded as index arrays, applying Floyd's tortoise-and-hare algorithm to find where a cycle begins.

Rho-Shaped Index Chain

You are given a list next_node of length n, where next_node[i] is the index of the node that node i points to. This encodes an implicit singly-linked list starting at index 0.

It is guaranteed that following the chain from index 0 will eventually enter a cycle (making the shape of the Greek letter ρ — a "tail" leading into a loop).

Your task is to return the index where the cycle begins — the first node that is visited twice when you follow the chain starting from index 0.

How to read the chain

Starting at 0, you repeatedly move to next_node[current]. For example, if next_node = [1, 2, 3, 1], the traversal is:

0 → 1 → 2 → 3 → 1 → 2 → 3 → ...

The cycle entry point is 1 because that is the first node revisited.

Constraints

  • 2 ≤ n ≤ 2000
  • 0 ≤ next_node[i] < n for all i
  • Following the chain from index 0 is guaranteed to reach a cycle.
  • The tail (pre-cycle portion) may have length 0 (meaning index 0 itself is inside the cycle).
  • There is exactly one cycle in the reachable portion of the chain.

Examples

Example 1

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

Output: 1

Example 2

Input: find_cycle_entry([2, 0, 2])

Output: 2

Example 3

Input: find_cycle_entry([1, 2, 3, 4, 2])

Output: 2

Hints

Hint 1

Use two pointers (slow moves one step, fast moves two steps) until they meet inside the cycle.

Hint 2

After the tortoise and hare meet, reset one pointer to the start (index 0) and advance both one step at a time; they meet exactly at the cycle entry.

Hint 3

The tail length can be zero — make sure your implementation handles the case where index 0 is already part of the cycle.