Find the Duplicate Number solution explained
Find the Duplicate Number is solved without changing the array and with O(1) extra memory by treating each value as a pointer to the next index. Following those pointers from index 0 must enter a cycle, and the cycle's entrance is the repeated value, which Floyd's tortoise and hare finds in O(n) time. A binary search over the value range that counts elements is a simpler O(n log n) alternative.
By Evin JohnPublished 7 min read
The problem, restated
You are given an array of length n + 1. Every element is a whole number from 1 to n. By the pigeonhole principle at least one value must appear twice, and the problem promises that only one distinct value repeats, though it may appear more than twice. Return that value. The common constraints are the interesting part: do not modify the array, and use only constant extra memory.
| Array | Answer | Note |
|---|---|---|
| [3, 1, 4, 2, 4] | 4 | n = 4, five slots, 4 appears twice |
| [2, 2, 2, 2] | 2 | One value fills most of the array |
| [1, 1] | 1 | Smallest possible case, n = 1 |
| [5, 3, 1, 5, 2, 4] | 5 | The duplicate does not have to be adjacent |
Why it is a favorite
Without constraints it is a one-liner. With them, it checks whether you can reframe a problem: the array is secretly a linked list, and linked-list cycle detection solves it. Interviewers also watch how you respond as each easy answer is ruled out, which says a lot about how you handle changing requirements.
Follow-ups
- Prove a duplicate must exist. n + 1 items in n possible values: pigeonhole.
- Why does index 0 matter? No value equals 0, so nothing points back to index 0; so it can never be inside the cycle and is a safe place to start the walk.
- What if several values repeat? Floyd's method then finds only one of them; a set-based approach is needed to list them all.
- What if you may modify the array? Mark visited values by negating nums at that index, then restore the signs.
Answers that break the constraints
- A set of seen values. One pass, O(n) time, but O(n) memory.
- Sort, then look for equal neighbors. O(n log n), O(1) extra if sorted in place, but it modifies the input.
- Compare every pair. O(1) memory and no modification, but O(n²) time. Correct, and a fair thing to mention as the strict-constraints baseline.
A middle ground that meets both constraints is binary search on the value, not on positions. For a candidate mid, count how many elements are at most mid. Without a duplicate at or below mid, that count would be at most mid. If the count is larger, the duplicate lies in 1..mid; otherwise it is above mid. Each count is O(n) and there are O(log n) rounds.
def find_duplicate_by_counting(nums):
lo, hi = 1, len(nums) - 1
while lo < hi:
mid = (lo + hi) // 2
at_most_mid = sum(1 for x in nums if x <= mid)
if at_most_mid > mid:
hi = mid
else:
lo = mid + 1
return loTurning the array into a linked list
Think of index i as a node whose next pointer is nums[i]. Start at index 0 and keep following. Because every value is between 1 and n, you never leave the array, and with finitely many nodes the walk must eventually repeat, so it enters a cycle. The node where the walk first joins the cycle has two arrows pointing into it: one from the path that led in, one from inside the cycle. Two arrows into the same index means two positions hold the same value, so that index is the duplicate.
Floyd's method finds that entrance. Phase one: move slow one step and fast two steps until they land on the same node; they must meet inside the cycle. Phase two: put slow back at the start and move both one step at a time. The point where they meet again is the cycle's entrance. The reason is a distance argument: the distance from the start to the entrance equals the distance from the meeting point forward to the entrance, measured around the cycle.
def find_duplicate(nums):
slow = fast = nums[0]
while True: # phase 1: meet somewhere inside the cycle
slow = nums[slow]
fast = nums[nums[fast]]
if slow == fast:
break
slow = nums[0]
while slow != fast: # phase 2: walk to the cycle entrance
slow = nums[slow]
fast = nums[fast]
return slowfunction findDuplicate(nums) {
let slow = nums[0];
let fast = nums[0];
do {
slow = nums[slow];
fast = nums[nums[fast]];
} while (slow !== fast);
slow = nums[0];
while (slow !== fast) {
slow = nums[slow];
fast = nums[fast];
}
return slow;
}Both versions start one step in, at nums[0], rather than at index 0 itself. That is equivalent, because both pointers skip the same first step, and it keeps the loops short. Trace [3, 1, 4, 2, 4]: the walk from index 0 goes 3, 2, 4, 4, 4, so it enters a loop at 4, and 4 is the answer.
Complexity
| Approach | Time | Extra memory | Leaves input unchanged? |
|---|---|---|---|
| Set of seen values | O(n) | O(n) | Yes |
| Sort and scan | O(n log n) | O(1) in place | No |
| All pairs | O(n²) | O(1) | Yes |
| Binary search on values | O(n log n) | O(1) | Yes |
| Floyd's cycle detection | O(n) | O(1) | Yes |
Inputs worth trying
- The smallest case, [1, 1].
- A duplicate that sits at its own index, such as [1, 3, 2, 2], where the cycle is a single position pointing to itself.
- The duplicate equal to n, the largest allowed value.
- A long path before the cycle, to check that phase two really walks to the entrance.
Frequent mistakes
- Returning the phase-one meeting point, which is inside the cycle but not necessarily the entrance.
- Resetting both pointers in phase two instead of only one.
- Using a while loop that checks slow == fast before the first move, so it exits at once because both start equal.
- Applying the method to arrays that do not meet the 1..n range rule, where indexes can run off the end.
How to explain it out loud
Fictional example
- Candidate
- If I treat each value as a pointer to an index, the array becomes a linked list, and it has to loop because every pointer stays in range.
- Candidate
- The repeated value is where the loop starts, because two different positions point to that index. So this is finding the start of a cycle.
- Candidate
- Floyd's method does that with two pointers: one at single speed and one at double speed until they meet, then both at single speed from the start and the meeting point. Linear time, constant memory, and I never write to the array.
Where to go next
Remove Nth Node From End of List uses two pointers with a fixed gap instead of two speeds. Copy List with Random Pointer is another problem where pointer identity, not values, carries the answer. For a change of structure, Invert Binary Tree moves from lists to trees.
Practicing with Natively
The hard part here is the reframing, so it pays to rehearse the explanation. During practice, Natively on Mac or Windows can read this problem from a screenshot and point toward the cycle view and the counting alternative, a useful check once you have tried it on your own. A transcript of your spoken mock shows whether you justified why the entrance is the duplicate. Read more about the AI interview assistant.
Questions people ask
How do you find the duplicate number without extra space?
Treat each value as a pointer to an index and follow the pointers from index 0. The path must enter a cycle, and its entrance is the duplicate. Floyd's tortoise and hare finds it in O(n) time and O(1) memory.
Why does the array contain a cycle?
Every value is between 1 and n, so following values as indexes never leaves the array, and with finitely many positions the walk must repeat.
Is there a simpler solution that does not modify the array?
Binary search on the value range: count elements at most mid; if the count exceeds mid, the duplicate is at most mid. That is O(n log n) time and O(1) memory.
Why not use a set or sort the array?
A set uses O(n) memory and sorting changes the input. The usual version of the problem forbids both.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
