Find All Numbers Disappeared in an Array

easy array hash map

Problem

Given an array nums with values in [1, n] (n = nums.length), return all integers in [1, n] that do not appear in nums. O(n) time, O(1) extra space.

Inputnums = [4, 3, 2, 7, 8, 2, 3, 1]
Output[5, 6]
Flag slot |x|-1 negative for every x; positives left mark missing indices.

def find_disappeared_numbers(nums):
    for x in nums:
        i = abs(x) - 1
        if nums[i] > 0:
            nums[i] = -nums[i]
    return [i + 1 for i, v in enumerate(nums) if v > 0]
function findDisappearedNumbers(nums) {
  for (const x of nums) {
    const i = Math.abs(x) - 1;
    if (nums[i] > 0) nums[i] = -nums[i];
  }
  const res = [];
  for (let i = 0; i < nums.length; i++) if (nums[i] > 0) res.push(i + 1);
  return res;
}
class Solution {
    public List<Integer> findDisappearedNumbers(int[] nums) {
        for (int x : nums) {
            int i = Math.abs(x) - 1;
            if (nums[i] > 0) nums[i] = -nums[i];
        }
        List<Integer> res = new ArrayList<>();
        for (int i = 0; i < nums.length; i++) if (nums[i] > 0) res.add(i + 1);
        return res;
    }
}
vector<int> findDisappearedNumbers(vector<int>& nums) {
    for (int x : nums) {
        int i = abs(x) - 1;
        if (nums[i] > 0) nums[i] = -nums[i];
    }
    vector<int> res;
    for (int i = 0; i < (int)nums.size(); i++) if (nums[i] > 0) res.push_back(i + 1);
    return res;
}
Time: O(n) Space: O(1)