Leetcode 448. Find All Numbers Disappeared in an Array
You are given an array nums
of size n
where nums
contains numbers in the range [1, n]
. Some elements appear twice, and some elements appear once. Find all the elements from 1
to n
that do not appear in nums
and return them in any order.
Input: nums = [4,3,2,7,8,2,3,1]
Output: [5,6]
n
?nums
array have all unique elements?nums
array be empty?To solve this problem, we’ll use an in-place algorithm to effectively mark the numbers in the array nums
to identify which numbers are missing. This approach will ensure O(1) auxiliary space, not including the output array.
nums
.num
, mark the number at index abs(num) - 1
as negative to indicate that abs(num)
is present in the array.i
that contains a positive value indicates that the number i + 1
is missing from the array.Here’s the C++ code to implement this approach:
#include <vector>
#include <cmath>
std::vector<int> findDisappearedNumbers(std::vector<int>& nums) {
std::vector<int> result;
// Mark each number's presence by negating the value at the corresponding index.
for (int i = 0; i < nums.size(); i++) {
int num = std::abs(nums[i]);
nums[num - 1] = -std::abs(nums[num - 1]);
}
// Collect indices with positive values, which indicates missing numbers.
for (int i = 0; i < nums.size(); i++) {
if (nums[i] > 0) {
result.push_back(i + 1);
}
}
return result;
}
Time Complexity: O(n), where n
is the length of the input array nums
. We iterate over the array twice: once for marking entries and once for collecting results.
Space Complexity: O(1) auxiliary space (not including the space for the output array). We modify the input array in place without using any additional significant space.
This approach efficiently identifies all the missing numbers within 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?