
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Find All Duplicates in an Array in C++
Suppose we have an array of integers, in range 1 ≤ a[i] ≤ n (n = size of array), here some elements appear twice and others appear once. We have to find all the elements that appear twice in this array. So if the array is [4,3,2,7,8,2,3,1], then the output will be [2, 3]
To solve this, we will follow these steps −
- n := size of array, make one array called ans
- for i in range 0 to n – 1
- x := absolute value of nums[i]
- decrease x by 1
- if nums[x] < 0, then add x + 1 into ans, otherwise nums[x] := nums[x] * (-1)
- return ans
Example(C++)
Let us see the following implementation to get a better understanding −
#include <bits/stdc++.h> using namespace std; void print_vector(vector<auto> v){ cout << "["; for(int i = 0; i<v.size(); i++){ cout << v[i] << ", "; } cout << "]"<<endl; } class Solution { public: vector<int> findDuplicates(vector<int>& nums) { int n = nums.size(); vector <int> ans; for(int i = 0; i < n; i++){ int x = abs(nums[i]); x--; if(nums[x] < 0) ans.push_back(x + 1); else nums[x] *= -1; } return ans; } }; main(){ Solution ob; vector<int> v = {4,3,2,7,8,2,3,1}; print_vector(ob.findDuplicates(v)); }
Input
[4,3,2,7,8,2,3,1]
Output
[2,3]
- Related Articles
- Finding all duplicate numbers in an array with multiple duplicates in JavaScript
- Find a Fixed Point in an array with duplicates allowed in C++
- Check for duplicates in an array in MongoDB?
- Find Duplicates of array using bit array in Python
- Find Duplicates of array using bit array in C++
- Remove duplicates and map an array in JavaScript
- How to find duplicates in an array using set() and filter() methods in JavaScript?
- Find All Numbers Disappeared in an Array in C++
- Unique sort (removing duplicates and sorting an array) in JavaScript
- Removing consecutive duplicates from strings in an array using JavaScript
- How to find all leaders in an array in Java?
- Remove duplicates from an array keeping its length same in JavaScript
- Golang Program To Remove Duplicates From An Array
- How to select all duplicates in MySQL?
- Remove All Adjacent Duplicates In String in Python

Advertisements