LeetCode #287 Medium

Find the Duplicate Number

An array of n + 1 integers holds values in [1, n]. One value repeats. Find it without modifying the array and in O(1) space.

arraytwo-pointersfloyd
Open on LeetCode ↗
02

Intuition

💡

Read each index as a pointer i → nums[i]. Because two indices share a value, this functional graph contains a cycle, and the duplicate is the cycle's entrance. Floyd's tortoise and hare finds that entrance without extra space.

03

Approach

1

The easy solutions each break a rule

A hash set finds the repeat instantly but uses O(n) space; sorting finds it but mutates the array. The problem forbids both. To respect 'read-only and O(1) space' we need to see hidden structure in the input — and there's a beautiful one: the values themselves can be read as pointers.

2

Read the array as a linked list with a cycle

Interpret each index as a pointer: i leads to nums[i]. Because there are n+1 slots but values only range over [1, n], two different indices must point to the same place — and that collision means following the pointers eventually revisits a node, i.e. forms a cycle. Crucially, the entrance of that cycle is exactly the duplicated value, because that's the value two indices point into.

3

Floyd's two-phase cycle finding

Now it's the classic 'find the start of a cycle' problem. Phase 1: move slow one hop and fast two hops until they meet somewhere inside the loop (a fast pointer must lap a slow one in a cycle). Phase 2: reset slow to the start and advance both one hop at a time; the distance arithmetic of Floyd's algorithm guarantees they collide precisely at the cycle's entrance — the duplicate. Only index reads, two variables: O(n) time, O(1) space, array untouched.

04

Solution & live demo

python
1class Solution:
2 def findDuplicate(self, nums):
3 slow = fast = nums[0]
4 while True:
5 slow = nums[slow]
6 fast = nums[nums[fast]]
7 if slow == fast:
8 break
9 slow = nums[0]
10 while slow != fast:
11 slow = nums[slow]
12 fast = nums[fast]
13 return slow
05

Edge cases

Duplicate appears many times, e.g. [2,2,2,2,2]

Floyd's method finds the cycle entrance regardless of how many times the value repeats.

Duplicate at the array's edges

Indexing by value, not position, makes the location in the array irrelevant to the cycle math.

Read-only requirement

Only index reads are used; the array is never written, satisfying the no-modify rule.

06

Complexity

Time
O(n)
Space
O(1)
Two phases, each linear; only two index variables.