KatInterview

Find the Entry Point of a Functional Rho-Shaped Sequence

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

Last updated

Tests cycle detection on an index-based "next" array by finding where the tail of a rho-shaped sequence first enters its cycle.

Rho-Shaped Sequence Entry Point

A rho-shaped sequence (named after the Greek letter ρ) starts at index 0, follows a chain of "next" pointers, then eventually loops back to some earlier index — forming a tail leading into a cycle.

You are given a list nxt of length n where nxt[i] is the next index to visit after index i. Starting from index 0 and following the chain, the sequence is guaranteed to eventually repeat (i.e., it is rho-shaped: a straight tail that enters a cycle).

Your task is to return the index at which the sequence first enters the cycle — the first index that is visited twice when following the chain from index 0.

How the chain works

Beginning at index 0, you visit:

0 → nxt[0] → nxt[nxt[0]] → ...

The first index you reach that you have already visited before is the cycle entry point.

Constraints

  • 2 ≤ n ≤ 2000
  • 0 ≤ nxt[i] < n for all i
  • nxt encodes exactly one rho-shaped sequence starting from index 0 (the sequence starting at 0 will always eventually cycle; the cycle entry point is always reachable from 0)
  • There is exactly one correct answer.

Examples

Example 1

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

Output: 1

Example 2

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

Output: 0

Example 3

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

Output: 2

Hints

Hint 1

Try Floyd's tortoise-and-hare algorithm: move one pointer one step at a time and another two steps at a time until they meet inside the cycle.

Hint 2

Once the two pointers meet, reset one pointer to the start (index 0) and advance both one step at a time; their next meeting point is the cycle entry.

Hint 3

Alternatively, because n ≤ 2000 you can simply walk the chain while recording visited indices in a set, returning the first index you see for the second time.