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 in an Array INPUT nums array (length n=8) 4 i=0 3 i=1 2 i=2 7 i=3 8 i=4 2 i=5 3 i=6 1 i=7 Constraints: - Values in range [1, n] - Each appears at most 2x - n = 8, range = [1,8] [4,3,2,7,8,2,3,1] = Duplicate values ALGORITHM STEPS Index Marking Method 1 Iterate Array For each num, get index: idx = abs(num) - 1 2 Check Sign If nums[idx] is negative, num is a duplicate! 3 Mark as Visited Negate nums[idx]: nums[idx] = -nums[idx] 4 Collect Duplicates Add num to result when negative found Example: num=2 (first) idx = 2-1 = 1 nums[1]=3 (positive) Mark: nums[1]=-3 Later: 2 found again! FINAL RESULT Array after marking: -4 -3 -2 -7 8 2 -3 -1 Duplicates Detected When: num=2: idx=1, nums[1]=-3 num=3: idx=2, nums[2]=-2 Already negative! Output: [2, 3] OK - Duplicates Found Complexity: Time: O(n) Space: O(1) Key Insight: Since values are in range [1,n], we can use the value as an index (value-1) to mark visited elements. By negating nums[idx], we create a "visited" marker. If we encounter a negative value at that index again, we know the number is a duplicate. This achieves O(1) space by using the input array itself as storage! TutorialsPoint - Find All Duplicates in an Array | Index Marking (Constant Space)
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