Find All Numbers Disappeared In An Array Problem
Description
LeetCode Problem 448.
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 <= 10^5
- 1 <= nums[i] <= n
Solution
Approach: Mark Present Values with Negative Signs
A boolean array of size n would solve this directly, but it costs O(n) extra space. The input array can hold the same information.
Every value lies in [1, n], so value v can own index v - 1. All values start positive, which leaves the sign of each slot free to store one bit: "v appears in the array".
- For each element
x, computeslot = |x| - 1and makenums[slot]negative (if it is not already). - Walk the array again. Any index
iwhose value is still positive was never marked, soi + 1is missing.
Take the absolute value in step 1: by the time we reach an element, it may already have been negated because of an earlier value, but its absolute value is still the original number. Also only negate a positive slot; negating twice would flip a duplicate's mark back to "unseen".
For [4,3,2,7,8,2,3,1], slots 0, 1, 2, 3, 6, 7 get marked, slots 4 and 5 stay positive, and the answer is [5, 6].
The array is modified; flip all values back to positive afterwards if it must be preserved.
Complexity: O(n) time and O(1) extra space besides the answer, where n is the length of nums.
class Solution:
def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
# Value v owns index v - 1: make that slot negative to mark "v appears".
for x in nums:
slot = abs(x) - 1 # the element may already be negated, so read it without its sign
if nums[slot] > 0:
nums[slot] = -nums[slot]
# Slots that stayed positive belong to values that never appeared.
return [i + 1 for i in range(len(nums)) if nums[i] > 0]
Now write it from memory
Close the write-up and solve it yourself against the tests.