Find All Duplicates in an Array - Problem

You're given an integer array nums of length n where all integers are in the range [1, n] and each integer appears at most twice. Your task is to find and return an array containing all integers that appear exactly twice.

๐ŸŽฏ Challenge: Can you solve this in O(n) time using only O(1) extra space (excluding output space)?

Example: Given [4,3,2,7,8,2,3,1], the duplicates are [2,3] since they each appear twice.

Input & Output

example_1.py โ€” Basic Case
$ Input: [4,3,2,7,8,2,3,1]
โ€บ Output: [2,3]
๐Ÿ’ก Note: Numbers 2 and 3 each appear exactly twice in the array, so they are the duplicates we need to return.
example_2.py โ€” Single Duplicate
$ Input: [1,1,2]
โ€บ Output: [1]
๐Ÿ’ก Note: Only the number 1 appears twice, so it's the only duplicate to return.
example_3.py โ€” No Duplicates
$ Input: [1]
โ€บ Output: []
๐Ÿ’ก Note: Single element array cannot have duplicates, so return empty array.

Visualization

Tap to expand
Array as Hash Table: The Magic of Index MappingStep 1: Initial Array [4,3,2,7,8,2,3,1]43278231Index: 0 1 2 3 4 5 6 7Step 2: Processing element 2 (second occurrence)Current element: 2 โ†’ Check index: 2-1 = 1-4-3-2-7-823-1nums[1] is already negative!This means 2 was seen before โ†’ Duplicate found!๐Ÿ’ก Key InsightUse array indices as hash keys:Number N maps to index N-1Negative values = "already seen"๐ŸŽฏ Result: Constant space, linear time - optimal solution!
Understanding the Visualization
1
Read Current Element
Take the absolute value of current element to get the actual number
2
Calculate Target Index
Subtract 1 from the number to get the corresponding array index (1-indexed to 0-indexed)
3
Check Marker
If the value at target index is negative, this number was seen before - it's a duplicate!
4
Set Marker
If positive, make it negative to mark this number as 'seen' for future iterations
Key Takeaway
๐ŸŽฏ Key Insight: Transform constraints into advantages - use the [1,n] range property to create an in-place hash table with negative markers!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Single pass through the array with O(1) hash set operations

n
2n
โœ“ Linear Growth
Space Complexity
O(n)

Hash set can store up to n elements in worst case

n
2n
โšก Linearithmic Space

Constraints

  • n == nums.length
  • 1 โ‰ค n โ‰ค 105
  • 1 โ‰ค nums[i] โ‰ค n
  • Each integer appears at most twice
Asked in
Google 45 Amazon 38 Meta 29 Microsoft 22
78.5K Views
High Frequency
~18 min Avg. Time
1.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