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
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
โ Linear Growth
Space Complexity
O(n)
Hash set can store up to n elements in worst case
โก Linearithmic Space
Constraints
- n == nums.length
- 1 โค n โค 105
- 1 โค nums[i] โค n
- Each integer appears at most twice
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code