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, you need to find all the integers that appear twice.
You should implement an algorithm that runs in O(n)
time and uses O(1)
extra space (excluding the input and output).
To satisfy the O(n)
time complexity and O(1)
extra space complexity, we can use the array indices to track visited numbers:
nums
.nums[i]
, use its absolute value val = abs(nums[i])
to find the index val - 1
.nums[val-1]
is positive, it indicates that the number val
has not been visited yet, so negate nums[val-1]
to mark it as visited.nums[val-1]
is already negative, it means the number val
has been encountered before, and hence it is a duplicate.This method ensures we only traverse the array once (O(n)
) and use the array itself to keep track of visited elements, achieving O(1)
extra space complexity.
import java.util.ArrayList;
import java.util.List;
public class Solution {
public List<Integer> findDuplicates(int[] nums) {
List<Integer> duplicates = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
int val = Math.abs(nums[i]);
if (nums[val - 1] < 0) {
duplicates.add(val);
} else {
nums[val - 1] = -nums[val - 1];
}
}
return duplicates;
}
}
O(n)
, where n
is the length of the input array nums
. We iterate through the array once.O(1)
, excluding the space used for the output list since we are directly modifying the input array to achieve the solution.This approach efficiently finds all the duplicates with the given constraints.
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?