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
- Two different indexes hold the duplicate value, so two "nodes" point to the same next node. That is exactly where a cycle starts.
- Run Floyd's algorithm:
slow = nums[slow],fast = nums[nums[fast]], until they meet. - 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.