Find All Numbers Disappeared in an Array
Difficulty: Easy · Pattern: Hashing · LeetCode #448
nums has length n and values in [1, n], some repeated. Return all values in [1, n] that don't appear, in increasing order. Follow-up: no extra space (besides the output).
Examples
text
[4, 3, 2, 7, 8, 2, 3, 1] → [5, 6]
[1, 1] → [2]Hints
- A set works with O(n) space.
- Use the array itself as the set: values map to indices.
Approach
For each value v, mark index |v| − 1 by making nums[|v| − 1] negative (use abs, since earlier marks may have negated it). Afterwards, every index i holding a positive number means i + 1 never appeared. O(n) time, O(1) extra space. (Restore the signs if the input must not be modified.)
Complexity
Time: O(n). Space: O(1) extra.
Python solution
def findDisappearedNumbers(nums):
for v in nums:
i = abs(v) - 1
if nums[i] > 0:
nums[i] = -nums[i]
return [i + 1 for i, v in enumerate(nums) if v > 0]JavaScript solution
function findDisappearedNumbers(nums) {
for (const v of nums) { const i = Math.abs(v) - 1; if (nums[i] > 0) nums[i] = -nums[i]; }
const out = [];
nums.forEach((v, i) => { if (v > 0) out.push(i + 1); });
return out;
}