Find the Duplicate Number
Find the Duplicate Number is LeetCode 287 (Medium). The array nums holds n + 1 integers, each between 1 and n. Exactly one value is repeated, possibly more than twice. Return that value.
- You may not modify
nums. - You may use only O(1) extra space.
Those two rules remove the usual tools: sorting changes the array, and a hash set takes O(n) memory. With n up to 10⁵, the follow-up asks for linear time as well.
- 1 <= n <= 10⁵
- nums.length == n + 1
- 1 <= nums[i] <= n
- All the integers in nums appear only once except for precisely one integer which appears two or more times.
Intuition
Read each index as a node with one arrow: index i points to index nums[i]. Every value is between 1 and n, so every arrow lands inside the array.
- Why a cycle appears: start at index 0 and keep following arrows. There are only
n + 1nodes, so the walk must eventually revisit one. - Why it is the duplicate: no value is 0, so nothing points back to index 0. The first node reached twice therefore has two arrows coming in, from two different indices holding the same value. That node's index is the duplicate.
So the task becomes: find where the cycle starts. Floyd's tortoise and hare does that with two pointers and no extra memory.
When a repeated value must be found without changing the array and with O(1) memory, look at the shape of the input: length n + 1 and values in 1..n point to reading nums[i] as a next-pointer, which turns the array into a linked list with a cycle.
Approach
Before reading on: follow i → nums[i] from index 0 on [1,3,4,2,2] and write down the indices you visit. Which index do you reach twice, and how is it related to the answer? Aim for O(n) time and O(1) space.
Two ways to solve it
Read nums[i] as a pointer and find where the cycle starts.
- Meets every rule: linear time, no extra memory, array untouched.
- Needs the proof: the second walk must be explained.
The answer the follow-up is asking for.
Guess a value mid and count how many numbers are at most mid.
- Easy to justify: a count above
midmeans the duplicate is at mostmid. - Slower: one full pass per guess.
A safe answer if the cycle idea does not come to you.
Both keep the array unchanged and use O(1) memory. Floyd's method also runs in linear time, so the steps, code and demo follow it; the binary search code comes after the demo.
Start both pointers at index 0
Set slow = fast = 0. Index 0 is a safe start because no value is 0, so it is the head of the list and never part of the cycle.
Race until the pointers meet
Repeat slow = nums[slow] and fast = nums[nums[fast]] until they are equal. Inside the cycle the fast pointer gains one node per round, so it is bound to catch the slow one; the meeting node is somewhere on the cycle.
Send one pointer back to the start
Set slow = 0 and leave fast at the meeting node. The distance from index 0 to the cycle entry equals the distance from the meeting node forward to the entry, counted around the cycle.
Walk both one step at a time
Repeat slow = nums[slow] and fast = nums[fast] until they meet again. Because both are the same number of steps from the entry, they arrive there together. Return that index: it is the duplicate value.
Code in Python, C++ and Java
Binary search on the value
Search over the values 1 to n, not over positions. Without a duplicate at or below mid, at most mid numbers could be <= mid. So a count above mid puts the duplicate in [lo, mid], and otherwise it is in [mid + 1, hi].
Common pitfalls
Returning the first meeting point
if slow == fast:
return slowslow = 0
while slow != fast:
slow = nums[slow]
fast = nums[fast]
return slowThe pointers first meet somewhere on the cycle, not necessarily at its entry. On [1,3,4,2,2] they meet at index 4, but the duplicate is 2.
Keeping the double step in the second walk
while slow != fast:
slow = nums[slow]
fast = nums[nums[fast]]while slow != fast:
slow = nums[slow]
fast = nums[fast]The second walk works only because both pointers are the same distance from the entry and move at the same speed. On [1,3,4,2,2] the double step keeps fast circling the cycle at a different pace, and the pointers meet at index 4, so the code returns 4 instead of 2.
Marking visited values by flipping signs
for x in nums:
if nums[abs(x)] < 0:
return abs(x)
nums[abs(x)] *= -1slow = fast = 0 # then Floyd's two walks
It finds the duplicate in one pass and passes the online tests, but it writes to nums, which the problem forbids. On [1,3,4,2,2] the array comes back as [1,-3,-4,-2,-2], and an interviewer will usually check this first.
Edge cases
[2,2,2,2,2]Index 0 points to 2 and index 2 points to itself, so the cycle is one node long. Both walks end at index 2 and the answer is 2.
[3,1,3,4,2]Index 1 points to itself and is not on the path from index 0. The walk from 0 still reaches the cycle 3 → 4 → 2 → 3 and returns 3.
Complexity
slow enters it, and the second walk covers the tail once. Only two indices are stored.Find the Duplicate Number FAQ
Why must a duplicate exist?
It is the pigeonhole principle: n + 1 numbers are placed into only n possible values, 1 to n, so at least two of them share a value.
Why does the second walk end exactly at the entry?
Say the tail has a nodes, the cycle has c nodes, and the pointers meet b steps past the entry. Slow walked a + b steps and fast walked twice that, so the extra a + b steps are whole laps: a + b is a multiple of c. Walking a more steps from the meeting point therefore lands on the entry, and so does walking a steps from index 0.
Is this the same as Linked List Cycle II?
Yes, apart from the input. LeetCode 142 hands you real nodes; here the next pointer of index i is nums[i], and the node index where the cycle starts is the answer.