CodeArchon

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.

1def duplicate_detective(nums: list[int]) -> int:
2 slow = fast = nums[0]
3 while True:
4 slow = nums[slow]
5 fast = nums[nums[fast]]
6 if slow == fast:
7 break
8 slow = nums[0]
9 while slow != fast:
10 slow = nums[slow]
11 fast = nums[fast]
12 return slow
Variables
slow=1
fast=1

How to think about it

  1. Values in [1..n] with length n+1 means some value appears ≥ twice.
  2. Two indices with the same value point to the same next → a cycle forms.
  3. Phase 1: slow + fast meet inside the cycle.
  4. 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 12
{"nums":[1,3,4,2,2],"values":[1,3,4,2,2]}
Example 23
{"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