Find All Duplicates in an Array

medium array hash map

Problem

Given an integer array nums where 1 ≤ nums[i] ≤ n and n = nums.length, return every element that appears twice. Solve in O(n) time and O(1) extra space (modifying nums is allowed).

Inputnums = [4, 3, 2, 7, 8, 2, 3, 1]
Output[2, 3]
When we visit a value x, flip nums[|x|−1] negative; a second visit finds it already negative.

def find_duplicates(nums):
    res = []
    for x in nums:
        idx = abs(x) - 1
        if nums[idx] < 0:
            res.append(abs(x))
        else:
            nums[idx] = -nums[idx]
    return res
function findDuplicates(nums) {
  const res = [];
  for (const x of nums) {
    const idx = Math.abs(x) - 1;
    if (nums[idx] < 0) res.push(Math.abs(x));
    else nums[idx] = -nums[idx];
  }
  return res;
}
class Solution {
    public List<Integer> findDuplicates(int[] nums) {
        List<Integer> res = new ArrayList<>();
        for (int x : nums) {
            int idx = Math.abs(x) - 1;
            if (nums[idx] < 0) res.add(Math.abs(x));
            else nums[idx] = -nums[idx];
        }
        return res;
    }
}
vector<int> findDuplicates(vector<int>& nums) {
    vector<int> res;
    for (int x : nums) {
        int idx = abs(x) - 1;
        if (nums[idx] < 0) res.push_back(abs(x));
        else nums[idx] = -nums[idx];
    }
    return res;
}
Time: O(n) Space: O(1)