LeetCode Solutions

442. Find All Duplicates in an Array

Time: $O(n)$

Space: $O(1)$

			

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;
  }
};
			

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;
  }
}
			

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