442. Find All Duplicates in an Array(Solution || Leetcode medium || Java)

Palakkgoyal
1 min readNov 21, 2022

--

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.

You must write an algorithm that runs in O(n) time and uses only constant extra space.

Example 1:

Input: nums = [4,3,2,7,8,2,3,1]
Output: [2,3]

Example 2:

Input: nums = [1,1,2]
Output: [1]

Example 3:

Input: nums = [1]
Output: []

Constraints:

  • n == nums.length
  • 1 <= n <= 105
  • 1 <= nums[i] <= n
  • Each element in nums appears once or twice.

Solution:

class Solution {
public List<Integer> findDuplicates(int[] nums) {
//As the range is 1 to n, hence, we will use cycle sort to
// solve this question
List<Integer> ans = new ArrayList<>();

int i = 0;

while(i < nums.length){//Applying cycle sort
int correct = nums[i] - 1;

if(nums[i] != nums[correct]){
int temp = nums[i];
nums[i] = nums[correct];
nums[correct] = temp;
}
else{
i++;
}
}

for(int j = 0; j < nums.length; j++){//Adding duplicates
if(nums[j] != j+1){
ans.add(nums[j]);
}
}

return ans;
}
}

Thank you for reading. If you have any queries then, please let me know in the comment section. I will surely be responsive toward it.

--

--

Palakkgoyal
Palakkgoyal

Written by Palakkgoyal

Solutions to all your coding related problems at one point. DSA question on daily basis and much more.

No responses yet