TRT
Sign in
mediumFoundationsLeetCode#Floyd's cycle detection#array as function

Find the duplicate number

An array of n + 1 numbers from 1 to n contains one repeated value. Find it without modifying the array and with O(1) extra space, by treating the array as a linked list with a cycle.

The Runtime Theory Team1 min read
Taught inFast and slow pointersTwo pointers walking a list at different speeds find its middle, the node n from the end, and whether it loops back on itself, all in one pass with O(1) memory.
Solve it

Solving happens on the judge — come back and mark it done

Sample cases

innums = [1, 3, 4, 2, 2]

out2

innums = [3, 1, 3, 4, 2]

out3

innums = [3, 3, 3, 3, 3]

out3

Given an array of n + 1 integers where each is between 1 and n, exactly one value repeats (possibly more than twice). Return it, without modifying the array and using only O(1) extra space.

Before you code

Sorting modifies the array, and a set uses O(n) space. Instead, read the array as a linked list: from index i, the next index is nums[i]. Index 0 is never a target, because values start at 1, so it is a natural head.

Hints

  1. Two different indexes hold the duplicate value, so two "nodes" point to the same next node. That is exactly where a cycle starts.
  2. Run Floyd's algorithm: slow = nums[slow], fast = nums[nums[fast]], until they meet.
  3. Reset one pointer to index 0 and move both one step at a time. Where they meet is the duplicate value.

Production & complexity notes

When solving Find the duplicate number on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Fast and slow pointers to reinforce the underlying pattern.

What it practices

Floyd's cycle detection on something that isn't a list, from Fast and slow pointers.

Not started

Sign in to save your learning progress.

Sign in to save