#442
Find All Duplicates in an Array
MediumArrayHash TableSortingHash MapArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution leverages the properties of the input array, using the indices to mark visited numbers. This way, we can identify duplicates without extra space for counting.
⚙️
Algorithm
3 steps- 1Step 1: Iterate through the array, using the absolute value of each number as an index.
- 2Step 2: Mark the number at that index by negating it.
- 3Step 3: If the number at that index is already negative, it means we've seen this number before, so add it to the duplicates list.
solution.py9 lines
1def findDuplicates(nums):
2 duplicates = []
3 for num in nums:
4 index = abs(num) - 1
5 if nums[index] < 0:
6 duplicates.append(abs(num))
7 else:
8 nums[index] = -nums[index]
9 return duplicatesℹ
Complexity note: This solution runs in linear time because we make a single pass through the array, and we use constant space since we modify the array in place.
- 1Use the properties of the input to optimize space and time.
- 2Negating values can help track visited indices without extra space.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.