Coding Interview PatternsFind All Duplicates in an Array
MediumCyclic Sort
Find All Duplicates in an Array
Explanation & Solution
Description
Given an integer array nums of length n where all integers are in the range [1, n] and each integer appears once or twice, return an array of all integers that appear twice.
You must write an algorithm that runs in O(n) time and uses only O(1) extra space.
Input:nums = [4, 3, 2, 7, 8, 2, 3, 1]
0
4
1
3
2
2
3
7
4
8
5
2
6
3
7
1
Output:[3, 2]
0
3
1
2
Explanation: 3 and 2 each appear twice.
Constraints
n == nums.length1 <= n <= 10^51 <= nums[i] <= n- Each element appears once or twice
Approach
Cyclic Sort pattern
1. Phase 1 — Cyclic Sort
- For each index
i, computej = nums[i] - 1(the correct index for that value) - If
nums[i] !== nums[j], swap — the value is misplaced - If
nums[i] === nums[j], either the value is already correct or a duplicate exists at indexj - In both cases, advance
i
2. Why Equality Means Duplicate or Correct
- If
j === i, thennums[i] = nums[j]trivially — value is in the right place - If
j !== ibutnums[i] = nums[j], both positions hold the same number — that's a duplicate - Swapping duplicates endlessly would cause an infinite loop, so we advance instead
3. Phase 2 — Collect Duplicates
- After the sort, scan every index
k - If
nums[k] !== k + 1, indexkshould holdk + 1but holds the duplicate valuenums[k]instead - Collect
nums[k]as a duplicate
🧠 Key Insight
- After cyclic sort, each position that holds the wrong value reveals a duplicate: the value at
nums[k]appears twice (once atnums[k]-1where it belongs, and once again atk)
Time
O(n)at most n swaps total in Phase 1Space
O(1) auxiliary (output array excluded)Visualization
Input:
[4, 3, 2, 7, 8, 2, 3, 1]
—
Press ▶ or use ← → to step through
Pointer iPointer jProcessedDone
19 steps