The Find All Numbers Disappeared in an Array coding problem provides an array of integers where each integer is in the range . Some numbers appear twice and others are missing. You need to find all the numbers in the range that do not appear in the array. The challenge is to solve it in time and extra space.
This is a high-signal "optimization" question asked by Meta, Microsoft, and Amazon. It tests whether you can use the input array itself to store state information. This Array interview pattern is vital for demonstrating that you can think about memory efficiency. It evaluations your ability to map values to indices and use a non-destructive "marking" technique.
This problem uses the Negative Marking interview pattern. Since all numbers are positive and in the range , the indices correspond to the values .
num in the array, calculate the index idx = abs(num) - 1.nums[idx] and, if it's positive, multiply it by -1 to "mark" that the value idx + 1 has been seen.i where nums[i] is still positive means the number i + 1 never appeared in the input.nums = [4, 3, 2, 7, 8, 2, 3, 1] ()
nums[3] as negative.nums[2] as negative.nums contains some negative and some positive values.nums[4] is positive. This means 5 is missing.nums[5] is negative. 6 is present.
Result: [5, 6].abs(nums[i]) when determining the index to mark, as that value might have already been turned negative by a previous marking.Problems that involve the range are perfect candidates for index-based marking or cyclic sort. Always look for ways to "flag" an index without losing the original value stored at that index.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Unique Number of Occurrences | Easy | Solve | |
| Minimum Number of Operations to Make Elements in Array Distinct | Easy | Solve | |
| Find the Difference of Two Arrays | Easy | Solve | |
| Max Pair Sum in an Array | Easy | Solve | |
| Distribute Candies | Easy | Solve |