KatInterview

Detect Functional-Graph Cycle Start on an Index Array

Linked ListsAuto-graded · 17 test cases
MediumAuto-gradedLinked Listslinked listscycle detectiontwo pointers

Last updated

Tests cycle detection (Floyd's or similar) on an implicit linked list encoded as a next-pointer array, requiring the candidate to find where the cycle begins.

Functional Graph Cycle Start

You are given a list next_node of length n. Each element next_node[i] is an integer in [0, n-1], meaning "from node i, follow the pointer to node next_node[i]."

Starting from index 0, repeatedly follow pointers:

0 → next_node[0] → next_node[next_node[0]] → …

Because n is finite and every node has exactly one outgoing edge, this path must eventually revisit a node — forming a rho (ρ) shape: a (possibly empty) tail leading into a cycle.

Your task is to return the index of the node where the cycle begins — i.e., the first node that is visited twice when following the chain from index 0.

How the cycle entry is defined

Walk the chain from index 0. The cycle-entry node is the first index that appears more than once in that infinite walk. Equivalently, it is the node v such that some earlier position in the walk also landed on v, and no node before v in the walk satisfies that property.

Constraints

  • 1 ≤ n ≤ 2000
  • 0 ≤ next_node[i] ≤ n - 1 for all i
  • The chain starting from index 0 is guaranteed to eventually cycle (always true for a finite functional graph).
  • If next_node[0] == 0, then index 0 is a self-loop and is its own cycle entry.

Examples

Example 1

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

Output: 2

Example 2

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

Output: 0

Example 3

Input: find_cycle_start([0])

Output: 0

Hints

Hint 1

Try keeping a visited set as you walk the chain; the first repeated index is the answer — but can you do it in O(1) extra space?

Hint 2

Floyd's tortoise-and-hare algorithm detects a cycle in O(n) time and O(1) space; after the two pointers meet inside the cycle, reset one pointer to the start and advance both one step at a time to find the entry.

Hint 3

When both pointers move at speed 1 after the meeting step, the step at which they coincide gives you the cycle-entry node directly.