KatInterview

Find the Duplicate and Cycle Length in a Functional Graph

Linked ListsAuto-graded · 17 test cases
MediumAuto-gradedLinked Listslinked listscycle detectionFloyd's algorithm

Last updated

Tests cycle detection on an index-as-next-pointer array to find the single duplicate value and the length of the cycle it creates.

Functional Graph Cycle Detective

You are given a list nodes of n + 1 integers where every value is in the range [1, n] inclusive. Because there are n + 1 values but only n distinct labels, exactly one label appears twice.

Interpret the list as a functional graph: node at index i has a directed edge to node at index nodes[i]. Because one value is repeated, this graph contains exactly one cycle.

Your task is to return a tuple (duplicate, cycle_length) where:

  • duplicate — the integer label that appears exactly twice (this label is the entry point of the cycle).
  • cycle_length — the number of nodes that form the cycle (i.e., the length of the smallest cycle reachable from index 0).

How the traversal works

Starting from index 0, follow the chain:

index 0  →  index nodes[0]  →  index nodes[nodes[0]]  →  …

Because exactly one value is duplicated, this chain will eventually revisit a node, forming a rho (ρ) shaped path: a tail leading into a cycle.

Constraints

  • 2 ≤ len(nodes) ≤ 2 000
  • len(nodes) == n + 1
  • Every element of nodes is in [1, n] where n = len(nodes) - 1
  • Exactly one value in nodes appears exactly twice; all others appear exactly once
  • The answer (duplicate, cycle_length) is unique
  • nodes[0] is never part of a duplicate (index 0 is always the tail start, not a cycle node itself) — the traversal from index 0 is guaranteed to reach the cycle

Examples

Example 1

Input: find_duplicate_and_cycle_length([2, 1, 2])

Output: [2, 1]

Example 2

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

Output: [3, 1]

Example 3

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

Output: [2, 4]

Hints

Hint 1

Think of each element nodes[i] as the 'next pointer' of node i — you can simulate a linked list walk starting at index 0 without building any explicit structure.

Hint 2

Floyd's tortoise-and-hare algorithm detects the meeting point inside the cycle; a second phase (reset one pointer to the start and advance both one step at a time) finds the exact entry point — that entry point index equals the duplicate value.

Hint 3

Once you know the entry point, measure the cycle length by advancing a single pointer around the loop and counting steps until it returns to the entry point.