Skip to content

442. Find All Duplicates in an Array 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
 public:
  vector<int> findDuplicates(vector<int>& nums) {
    vector<int> ans;

    for (const int num : nums) {
      nums[abs(num) - 1] *= -1;
      if (nums[abs(num) - 1] > 0)
        ans.push_back(abs(num));
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
  public List<Integer> findDuplicates(int[] nums) {
    List<Integer> ans = new ArrayList<>();

    for (final int num : nums) {
      nums[Math.abs(num) - 1] *= -1;
      if (nums[Math.abs(num) - 1] > 0)
        ans.add(Math.abs(num));
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
  def findDuplicates(self, nums: List[int]) -> List[int]:
    ans = []

    for num in nums:
      nums[abs(num) - 1] *= -1
      if nums[abs(num) - 1] > 0:
        ans.append(abs(num))

    return ans