442. Find All Duplicates in an Array ¶ Time: $O(n)$ Space: $O(1)$ C++JavaPython 1 2 3 4 5 6 7 8 9 10 11 12 13 14class 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 13class 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 10class 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