DSA problem
Find All Numbers Disappeared in an Array
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.
A straightforward solution uses a hash set of seen values, but the elegant optimal solution treats the array itself as a hash table. Because every value is in the range [1, n], each value v corresponds to index v - 1. By negating the number at the index encoded by each value, the array marks which numbers are present. Indices that remain positive after this pass correspond to the missing numbers.
Follow up: Could you solve it without extra space and in O(n) runtime? (The output array does not count as extra space.)
Examples
nums = [4,3,2,7,8,2,3,1][5,6]nums = [1,1][2]nums = [2,2][1]Constraints
- n == nums.length
- 1 <= n <= 10^5
- 1 <= nums[i] <= n
3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.