Problem Description
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.
Key Insights
- The input array contains integers from 1 to n, so each value can be mapped to an index in the array.
- In-place modification can be achieved by marking the values at these mapped indices to indicate presence.
- By iterating over the array after marking, the indices that were not marked (i.e., still positive) correspond to the missing numbers.
- This solution avoids using extra space beyond the output array.
Space and Time Complexity
Time Complexity: O(n) Space Complexity: O(1) (excluding the space for the output array)
Solution
We iterate through the array and for each number, we determine its corresponding index (by taking the absolute value of the number and subtracting one). We then mark the number at that index as negative to indicate that the number (index + 1) exists in the array. Finally, we iterate through the array once more and collect all indices that still hold positive values; these indices correspond to numbers that did not appear in the original array.