Given an array nums
of n
integers where nums[i]
is in the range [1, n]
, return an array of all the integers in the range [1, n]
that do not appear in nums
.
Example 1:
Input: nums = [4,3,2,7,8,2,3,1] Output: [5,6]
Example 2:
Input: nums = [1,1] Output: [2]
Constraints:
n == nums.length
1 <= n <= 105
1 <= nums[i] <= n
Follow up: Could you do it without extra space and in O(n)
runtime? You may assume the returned list does not count as extra space.
This problem asks us to find all numbers within the range [1, n] that are missing from a given array nums
of length n, where each element in nums
is within the same range [1, n]. Two approaches are presented below, one using extra space and another using in-place manipulation.
This approach leverages a set (or boolean array in languages like Java and C++) to track the presence of each number in the input array.
Algorithm:
s
(or a boolean array s
of size n+1, initialized to false
).nums
. For each number x
, mark its presence in s
by adding it to the set (or setting s[x]
to true
).i
is not found in s
(or s[i]
is false
), add it to the result list.Time Complexity: O(n) - We iterate through the array twice. Set operations (add and check) are typically O(1) on average. Space Complexity: O(n) - We use a set (or boolean array) of size n to store the present numbers.
Code Examples: (See the provided code snippets in Python, Java, C++, Go, and TypeScript)
This approach cleverly uses the input array itself to track the presence of numbers without requiring extra space. It modifies the array in-place.
Algorithm:
x
, find the index i = abs(x) - 1
. If the number at that index nums[i]
is positive, change its sign to negative. This indicates the presence of x
. The use of abs(x)
prevents overwriting the sign if a number has already been encountered.nums[i]
is positive, then the number i + 1
is missing. Add it to the result list.Time Complexity: O(n) - We iterate through the array twice. Space Complexity: O(1) - We use constant extra space, not counting the output array.
Code Examples: (See the provided code snippets in Python, Java, C++, Go, and TypeScript). Note the use of abs()
to handle potential negative numbers resulting from the in-place marking.
Choosing the Best Approach:
Approach 1 is simpler to understand and implement. Approach 2 is more efficient in terms of space complexity if space is a critical constraint, but it modifies the input array, which might not always be desirable. Choose the approach that best suits the specific requirements of your problem and coding style.