KatInterview

Find the Start of a Cycle in a Functional Graph

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

Last updated

Tests cycle detection on index arrays by finding the entry node of a rho-shaped path in a functional graph encoded as a plain list.

Functional Graph Cycle Entry

A functional graph is a directed graph where every node has exactly one outgoing edge. Such a graph can be represented as a plain array next of length n, where next[i] is the index of the node that node i points to.

Starting from node 0, repeatedly following the next pointers traces a path that eventually enters a cycle (a rho-shaped path: a tail leading into a loop). Your task is to find the index of the first node that belongs to the cycle — i.e., the entry point where the tail meets the loop.

Formally, the cycle entry is the smallest-index node c such that:

  • c is reachable from node 0 by following next pointers, and
  • c lies on a cycle (there exists k ≥ 1 with next[next[...next[c]...]] = c after k steps).

If two nodes could both serve as the entry point (which cannot happen in a true functional graph starting from 0), the tie-break is the smaller index. However, the graph is guaranteed to have exactly one cycle entry reachable from 0.

Task

Implement:

def find_cycle_entry(next_arr: list[int]) -> int:

Given next_arr, a list of n integers where next_arr[i] is the successor of node i, return the index of the cycle entry node reachable from node 0.

Important notes:

  • Every node i satisfies 0 ≤ next_arr[i] < n, so no node is a dead end.
  • Node 0 always eventually enters a cycle (the graph is finite).
  • The cycle entry is unique for the path starting at 0.
  • You must use O(1) extra space (pointer manipulation / Floyd's algorithm); do not use a visited set.

Constraints

  • 2 ≤ n ≤ 2000
  • 0 ≤ next_arr[i] < n for all i
  • next_arr defines a valid functional graph (every node has exactly one outgoing edge)
  • The path from node 0 always reaches a cycle
  • The cycle entry reachable from 0 is unique

Examples

Example 1

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

Output: 2

Example 2

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

Output: 0

Example 3

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

Output: 1

Hints

Hint 1

Think of next_arr as a linked list where each node's 'pointer' is stored at that index. Floyd's tortoise-and-hare algorithm detects a meeting point inside the cycle — how do you then find the *entry* of the cycle?

Hint 2

After the fast and slow pointers meet inside the cycle, reset one pointer to the start (node 0) and advance both one step at a time; they will meet exactly at the cycle entry.

Hint 3

Be careful: the 'head' of this linked list is always node 0, not index 0 of the array in the traditional sense — the value next_arr[i] is the next node to visit, so start slow = 0, fast = 0 and take your first step before comparing.