Instruction::
To solve this problem in O(n) time and constant extra space, we can utilize the fact that all integers in the array are in the range [1, n] and each integer appears once or twice. We can iterate through the array and use each element as an index to mark the corresponding element as negative. If we encounter an element that is already negative, it means we have seen it before and it's a duplicate.
Code::
class Solution {
public List<Integer> findDuplicates(int[] nums) {
List<Integer> ans = new ArrayList<>();
int n = nums.length;
for (int i = 0; i < n; i++) {
int x = Math.abs(nums[i]);
if (nums[x - 1] < 0) {
ans.add(x);
}
nums[x - 1] *= -1;
}
return ans;
}
}