Find All Duplicates in an Array LeetCode Solution

Here, We see Find All Duplicates in an Array LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.

List of all LeetCode Solution

Find All Duplicates in an Array LeetCode Solution

Find All Duplicates in an Array LeetCode Solution

Problem Statement

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: []

Find All Duplicates in an Array LeetCode Solution C++

class Solution {
public:
    vector<int> findDuplicates(vector<int>& nums) {
        vector<int>ans;
        int n=size(nums);
        for(int i=0;i<n;i++){
            int x=abs(nums[i]);
            if(nums[x-1]<0){ 
                ans.push_back(x);
            }
            nums[x-1]*=-1;
        }
        return ans;        
    }
};Code language: PHP (php)

Find All Duplicates in an Array Solution Java

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;
    }
}Code language: PHP (php)

Find All Duplicates in an Array Solution JavaScript

var findDuplicates = function(nums) {
    const ans = [];
    const n = nums.length;
    for (let i = 0; i < n; i++) {
        const x = Math.abs(nums[i]);
        if (nums[x - 1] < 0) {
            ans.push(x);
        }
        nums[x - 1] *= -1;
    }
    return ans;
};Code language: JavaScript (javascript)

Find All Duplicates in an Array Solution Python

class Solution(object):
    def findDuplicates(self, nums):
        ans =[]
        n=len(nums)
        for x in nums:
            x = abs(x)
            if nums[x-1]<0:
                ans.append(x)
            nums[x-1] *= -1
        return ansCode language: HTML, XML (xml)
Scroll to Top