#287

Find the Duplicate Number

Medium Floyd's cycle on indexes

  1. Read
  2. Understand
  3. Hints
  4. Approach
  5. Solution
  6. Solved

?The problem

An array of n + 1 numbers has values in 1..n, so one value repeats (possibly many times). Find it without modifying the array and with O(1) extra space.

This is a short summary in our own words. Read the full statement and examples on LeetCode: open problem ↗

◎Understanding

Really asking: n+1 numbers in 1..n, so one repeats. Find it without changing the array or using extra memory.

Why this works: treat index → nums[index] as "next". Two indexes pointing to the same place form a loop, and the loop's entrance is the duplicate. Floyd's slow/fast pointers find it.

Example: [1, 3, 4, 2, 2]

path: 0 → 1 → 3 → 2 → 4 → 2 → 4 …loop is 2 → 4 → 2, entered at 2answer 2

✦Hints open one at a time

↗Approach

</>Solution (Java)

!Common mistake

Sorting or marking with negatives — both modify the array, which the problem forbids.