Statementâ–¼
Given an integer array, nums
, of length nums
are in the range
Note: Write an algorithm that runs in
O(n) time and uses only constant auxiliary space, excluding the space occupied by the output.
Constraints:
n= nums.length
1≤n≤103 1≤ nums[i]
≤n Each element in
nums
appears once or twice.
Solution
The essence of this problem is to identify duplicates in an array by marking elements as seen using their corresponding indexes. We can solve this problem using a cyclic sort approach, which sorts elements in the array by placing them in their correct positions. However, instead of fully sorting the array, we modify the approach to identify duplicates. If an index is already negative, it indicates a duplicate. After finding all duplicates, the algorithm restores the array to its original state and returns the list.
The basic algorithm to solve this problem will be:
For each element in
nums
, we determine its correct index, which should benums[i] - 1
.We haven’t encountered this number if the element at the
correct_idx
is positive. We mark it by negating the value atcorrect_idx
.If the element at
correct_idx
is already negative, it indicates that this number has been seen before, so it’s a duplicate. We add this number to ourduplicates
list.
After identifying duplicates, we restore the array to its original state by making all values positive again.
Finally, we return the final list of duplicates.
Let’s look at the following illustration to get a better understanding of the solution: