Leetcode 442. Find All Duplicates in an Array
Given an integer array nums
of length n
where all the integers of nums
are in the range [1, n]
and each integer appears once or twice, return an array of all the integers that appear twice.
You must write an algorithm that runs in O(n)
time and uses only constant extra space.
nums
be empty?
nums
are within the range [1, n]
?Since the problem requires O(n)
time complexity and O(1)
(constant) extra space, we can’t use additional data structures like hash maps or sets which would not satisfy the space constraint.
Instead, we can use the input array itself to keep track of numbers that we’ve seen before. Here’s the plan:
This approach works because we are utilizing the existing array to keep track of the numbers we’ve seen and leveraging the fact that the indices fall within a predictable range [1, n]
.
#include <vector>
#include <cmath>
using namespace std;
vector<int> findDuplicates(vector<int>& nums) {
vector<int> result;
for (int i = 0; i < nums.size(); ++i) {
int index = abs(nums[i]) - 1;
// If the value at this index is already negative, it means we have seen the number before
if (nums[index] < 0) {
result.push_back(abs(nums[i]));
} else {
nums[index] = -nums[index];
}
}
return result;
}
The time complexity of this solution is O(n)
because:
The space complexity is O(1)
(constant space):
result
vector to store duplicates can be considered as O(D)
, where D
is the number of duplicates. However, since D
can at most be n/2
, it is often acceptable to consider it as constant space relative to the input size (n
).Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?