Find All Duplicates in an Array - Problem

Given an integer array nums of length n where all the integers are in the range [1, n] and each integer appears at most twice, return an array of all the integers that appear exactly twice.

Constraint: You must write an algorithm that runs in O(n) time and uses only constant auxiliary space (excluding the space needed to store the output).

Since all numbers are in range [1, n], we can use the array indices cleverly to track which numbers we've seen before.

Input & Output

Example 1 — Multiple Duplicates
$ Input: nums = [4,3,2,7,8,2,3,1]
Output: [2,3]
💡 Note: Numbers 2 and 3 each appear exactly twice in the array. Number 2 appears at indices 2 and 5, number 3 appears at indices 1 and 6.
Example 2 — Single Duplicate
$ Input: nums = [1,1,2]
Output: [1]
💡 Note: Only number 1 appears twice (at indices 0 and 1). Number 2 appears once, so it's not included.
Example 3 — No Duplicates
$ Input: nums = [1]
Output: []
💡 Note: Array has only one element, so no number can appear twice. Return empty array.

Constraints

  • n == nums.length
  • 1 ≤ n ≤ 105
  • 1 ≤ nums[i] ≤ n
  • Each element in nums appears once or twice

Visualization

Tap to expand
Find All Duplicates: [4,3,2,7,8,2,3,1]Range [1, 8], find numbers appearing exactly twice43278231appears 2xappears 2xappears 2xappears 2xNumbers 2 and 3 appear exactly twice[2, 3]
Understanding the Visualization
1
Input
Array with numbers in range [1, n], some appear twice
2
Process
Track which numbers we've seen before
3
Output
Return array of numbers appearing exactly twice
Key Takeaway
🎯 Key Insight: Use the array indices themselves as a hash map by leveraging the constraint that numbers are in range [1, n]
Asked in
Google 28 Amazon 22 Microsoft 15 Apple 12
178.0K Views
Medium-High Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen