Last updated on July 19th, 2024 at 09:54 pm
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
Topics
Array
Companies
Pocketgems
Level of Question
Medium
![Find All Duplicates in an Array LeetCode Solution](https://i0.wp.com/totheinnovation.com/wp-content/uploads/2024/02/LeetCode-Problem-Solution.png?resize=200%2C200&ssl=1)
Find All Duplicates in an Array LeetCode Solution
Table of Contents
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: []
1. 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; } };
2. 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; } }
3. 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; };
4. 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 ans