algorythms
Cyclic Sort
LC #287Medium

Find the Duplicate Number (Cyclic Sort approach)

Cyclic Sort
AmazonGoogleMeta

Problem

Given an array of n+1 integers where each integer is in the range [1, n], find the duplicate number. You must not modify the array and must use O(1) extra space. The cyclic-sort approach leverages the fact that each number belongs at a specific index.

arraycyclic-sort

Constraints

  • 2 ≤ n ≤ 10⁵
  • 1 ≤ nums[i] ≤ n − 1
  • Must not modify the array; O(1) extra space

Example

Inputnums = [1, 3, 4, 2, 2]
Output2
Why

2 appears at indices 3 and 4; must find it without modifying the array

Hints — reveal one at a time