5. Find All Duplicates in an Array
Given an integer array nums
of length n
where all the integers of nums
are in the range [1, n]
and each integer appears once or twice, return an array of all the integers that appears twice.
Example 1:
Example 2:
Example 3:
Solution: (Hashset)
Basic solution extra space of O(n)
Solution: (Optimized)
Approach: when find a number i, flip the number at position i-1 to negative. if the number at position i-1 is already negative, i is the number that occurs twice.
Time Complexity: O(n) , Space Complexity: O(1)
Last updated