You are 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.
Note: You can return the integers in any order.
Example 1:
Input: nums = [4,3,2,7,8,2,3,1]
Output: [5,6]Example 2:
Input: nums = [1,1]
Output: [2]Constraints:
1 <= nums[i] <= nums.length <= 100,000Follow 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.
We need to find numbers in the range [1, n] that are missing from the array. A simple approach is to create a set containing all numbers from 1 to n, then remove each number we find in the array. Whatever remains in the set are the missing numbers.
1 to n.Instead of using a set, we can use a boolean array where mark[i] indicates whether the number i+1 is present in the input. We first mark all numbers that appear, then collect all indices where the mark is still false.
mark of size n, initialized to false.mark[num - 1] = true.1 to n:mark[i - 1] is false, add i to the result.After sorting, we can use a two-pointer technique to find missing numbers. We iterate through numbers 1 to n and use a pointer to track our position in the sorted array. If the current number is not found at the pointer position, it must be missing.
idx = 0.1 to n:idx forward while nums[idx] < num (skip duplicates and smaller values).idx reaches the end or nums[idx] > num, the number is missing; add it to the result.Since values are in range [1, n], we can use the input array itself as a marker. For each value v, we mark the position v-1 as visited by making it negative. After processing all values, any position that remains positive corresponds to a missing number.
abs(num) - 1.nums[idx] negative (use absolute value to handle already-negated elements).nums[i] > 0, the number i + 1 is missing; add it to the result.Since values are in the range [1, n] but indices are [0, n-1], it is easy to mix them up. When marking position i as visited, remember that value v maps to index v-1. Similarly, when checking which numbers are missing, index i corresponds to the number i+1.
When using negative marking, if you negate a value that is already negative, it becomes positive again and appears as if that position was never visited. Always use abs() before negating to ensure the value becomes negative regardless of its current sign.