This approach uses the properties of the array and its indices to track missing numbers. By iterating through the array and using the values to mark the corresponding indices, we can identify which indices were never marked and thus determine the missing numbers.
Steps:
nums
.Time Complexity: O(n) - where n is the number of elements in the array because we are iterating over the array twice.
Space Complexity: O(1) - as no additional data structure is used apart from the output list and input array is modified in-place.
1#include <vector>
2#include <cmath>
3using namespace std;
4
5vector<int> findDisappearedNumbers(vector<int>& nums) {
6 for (int i = 0; i < nums.size(); i++) {
7 int index = abs(nums[i]) - 1;
8 nums[index] = nums[index] > 0 ? -nums[index] : nums[index];
9 }
10 vector<int> result;
11 for (int i = 0; i < nums.size(); i++) {
12 if (nums[i] > 0) {
13 result.push_back(i + 1);
14 }
15 }
16 return result;
17}
This C++ implementation works similarly to the C solution by marking indices with negative values. After marking, it passes through the array to find all indices with positive values which correspond to the missing numbers.
In this approach, we utilize a set to only store unique numbers from 1 to n that appear in the input array. By comparing this set to the complete range of numbers, we can directly determine those not present in the input.
Steps:
nums
.Time Complexity: O(n)
Space Complexity: O(n), due to use of additional boolean array to track presence of numbers.
1class Solution:
2 def findDisappearedNumbers(self, nums):
3 num_set = set(nums)
4 return [i for i in range(1, len(nums) + 1) if i not in num_set]
This Python solution constructs a set of elements from the input list and compares against the range from 1 to n
to determine absent values.