mediumLinked ListAmazonGoogle
Duplicate Detective
An array of n+1 integers all in [1, n] must have a repeat. Find it without modifying the array in O(1) extra space.
Given `nums` of length n+1 with every value in [1..n], return the (unique) duplicated value. O(n) time, O(1) space, read-only input.
Choose approach
0
1
slowfast
2
3
4
1/7
Narrationstep 1 of 7
Treat indices as linked-list nodes with edge i → nums[i]. A duplicate value creates a cycle; find its entry using Floyd's algorithm.
Variables
slow=1
fast=1
How to think about it
- Values in [1..n] with length n+1 means some value appears ≥ twice.
- Two indices with the same value point to the same next → a cycle forms.
- Phase 1: slow + fast meet inside the cycle.
- Phase 2: reset slow to the start; stepping both one at a time converges at the cycle entrance = duplicate.
Edge cases to catch in interview
- Duplicate appears > 2 times — still works.
- Smallest case n=1 (length 2 array) — both entries are the duplicate.
Examples
Example 1
2{"nums":[1,3,4,2,2],"values":[1,3,4,2,2]}
Example 2
3{"nums":[3,1,3,4,2],"values":[3,1,3,4,2]}
Try your own input
SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed