Find the Duplicate Number
A medium Arrays problem included in Love Babbar 450, Striver A2Z. Below: the roles whose interviews prioritise this topic, and how to practise it.
- Topic
- Arrays
- Sheets
- 2
- Core for
- 25 roles
- Platform
- LeetCode
The problem
Given an array of n+1 integers where each integer is between 1 and n inclusive, find the duplicate number. There is guaranteed to be exactly one duplicate.
Example 1
- Input
- [1,3,4,2,2]
- Output
- 2
Example 2
- Input
- [3,1,3,4,2]
- Output
- 3
Example 3
- Input
- [1,1]
- Output
- 1
Constraints
- 2 <= n <= 10^5
- 1 <= arr[i] <= n
How to think about it
Updated 2026-09-09Every index pointing to arr[i] forms a directed edge in a functional graph. Because every value is between 1 and n while the array has n + 1 cells, the pigeonhole principle guarantees two different indices point to the same node, creating a cycle whose entry point is precisely the duplicate value.
Approaches, worst first
Visited hash set
time O(n) · space O(n)
Traverse the array and insert each element into a hash set. The first element already present in the set is the duplicate. Correct and quick to verify, but allocates linear extra memory.
In-place sign marking
time O(n) · space O(1)
Treat each value as an index and negate the value at that destination. If a destination is already negative, its index is the duplicate. Runs in linear time and constant space but permanently mutates the underlying input array.
Floyd cycle detectionWrite this one
time O(n) · space O(1)
Treat array values as next pointers: slow advances one step (arr[slow]), fast advances two steps (arr[arr[fast]]). Once they collide, reset slow to index 0 and advance both one step at a time until they meet at the cycle entrance.
Where people lose marks · 3
- Starting Floyd's algorithm at index `slow = 0` and `fast = 0` triggers the termination condition immediately before the pointers even move.
- Attempting in-place sign negation on a read-only or immutable input buffer fails at runtime.
- Binary searching on values instead of indices requires counting elements less than or equal to mid, which takes O(n log n) time and is slower than cycle finding.
Full solution
Floyd cycle detection over the value-as-pointer graph: it is O(n) time and O(1) space without mutating the input, which is what rules out the hash set and the sign-marking trick in an interview.
Python
def find_duplicate(nums: list[int]) -> int:
# values are indices, so nums[i] is a "next" pointer; the duplicate is the cycle entrance
slow = fast = nums[0]
while True:
slow = nums[slow]
fast = nums[nums[fast]]
if slow == fast:
break
# phase 2: the distance from the start to the entrance equals the distance from the meeting point
slow = nums[0]
while slow != fast:
slow = nums[slow]
fast = nums[fast]
return slow
JavaScript
function 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;
}
The theory behind it
Arrays — the ground this problem stands on. All Arrays problems
What Arrays is
An array is a row of fixed boxes laid side by side in computer memory, like numbered lockers in a hallway. Because each box occupies identical space and sits directly next to its neighbors, jumping to locker zero or locker ten thousand takes the exact same tiny fraction of time. Every box holds an item of the same type, addressed by an offset number called an index.
When to reach for it
Reach for an array when items arrive in a known sequence and need immediate retrieval by position number. Problems asking for running totals, prefix accumulations, cyclic rotations, or in-place rearrangements signal array mechanics. Whenever constraints require constant-time random lookups or contiguous cache scans across fixed collections, a flat sequence is the default container.
How the pattern works
Visualize a tape with zero-indexed slots stretching from start to end. Keep track of write and read cursors when modifying contents without allocating helper buffers. For running computations, maintain an invariant such as having processed all elements left of the current index while pending elements wait to the right. When modifying entries in place, consider scanning backwards from the end so unread data is not overwritten.
What each operation costs
| Operation | Time |
|---|---|
| look up element by index | O(1) |
| insert or delete at the start | O(n) |
| search an unsorted collection for a value | O(n) |
What usually goes wrong with Arrays
- Reading past the final index by checking index less than or equal to length instead of strictly less than length, triggering index out of bounds exceptions.
- Modifying length or removing elements during a forward iteration loop, which causes remaining items to shift left and skip validation on the next neighbor.
- Assuming dynamic resizing is costless inside nested loops, causing repeated memory reallocation copies when appending unknown quantities of items.
Which roles need this problem
Arrays is a core topic for these 25 roles — if you're targeting one of them, this problem is early in your path, not optional.
Secondary for 3 more roles, including Database Engineer, Bioinformatics Engineer, Networking Engineer.
Track this in your role's order
Pick your target role and all 370 problems — including this one — resequence to what that interview actually asks. Free.
Start freeMore Arrays problems
Problem set and role mapping as of .