How to find duplicates in an array
An array in C++ stores multiple values of the same data type in a single variable. We can also say that it's a collection of similar items. These items of the same data types in an array are its elements. We can access these elements using the index of the array.
A pictorial representation of arrays is shown below:
The length of this array is 5.
The data type of values stored in this array is an integer.
Find duplicates in an array
We are given an array of
Method 1: Use a nested loop for every element. If the element occurs more than once, store it in the hash map. Otherwise, check for the next element. Its time complexity would be
Method 2: Count the frequency of every element, and print the element with frequency 1+. We'll require to use an unordered set and unordered map for this method since the range of integers is unknown. Its time complexity is
Method 3: Use a simple hash map. If the elements in the array are from
Note: This will only work when all elements are in the range from 0 to
where is the size of the array.
Proposed solution
Our second method is the most efficient one since it takes less time and has total correctness.
Steps
Traverse the whole array from index 0 to
. Count the frequency of every element using the unordered map.
Put all the elements with a frequency of more than 1 into the set.
Return the set of elements with a frequency greater than 1.
Example
Input : size = 7 and array[] = {13, 2, 4, 2, 13, 5, 4}Output: 13, 2, 4Explanation: The numbers 13, 2 and 4 has frequency > 1
Code
#include <iostream>#include <unordered_set>#include <unordered_map>using namespace std;unordered_set<int> findDuplicates(int arr[], int size){int i = 0;unordered_map<int, int> freq; // Creating frequency mapwhile( i < size){freq[arr[i]]++; //counting freqi++;}unordered_set<int> duplicates;for (auto const &pair: freq){if (pair.second > 1) //checking second parameter > 1{duplicates.insert(pair.first);}}return duplicates;}int main(){int arr[] = {13, 2, 4, 2, 13, 5, 4};int n = sizeof(arr) / sizeof(*arr);unordered_set<int> duplicates = findDuplicates(arr, n);for (int i: duplicates){cout << i << ' ';}return 0;}
Explanation
Line 9–13: We count the frequency of every element—
freq[arr[i]]++.Line 15–20: We add elements into the set with a frequency of more than 1—
duplicates.insert(pair.first).
Time complexity
The time complexity here is
Free Resources