Find duplicates in a given array when elements are not limited to a range in C++

C++Server Side ProgrammingProgramming

Suppose we have an array of N integers. Here we will print the duplicates of the given array. If no such duplicates are present, then return -1. So if the array is like [12, 15, 12, 3, 6, 12, 3, 48, 56, 8, 48], then duplicates are: [12, 3, 48]

Here we will use the unordered map in C++. So at first when one element is taken, check whether that is present in the map or not, if this is present, then simply print that as duplicate, otherwise just add that into map.

Example

 Live Demo

#include<iostream>
#include<unordered_map>
using namespace std;
void displayDuplicates(int arr[], int n) {
   unordered_map<int, int> occurrence;
   for (int i=0; i<n; i++)
   occurrence[arr[i]]++;
   bool duplicate = false;
   unordered_map<int, int>:: iterator itr;
   for (itr=occurrence.begin(); itr!=occurrence.end(); itr++) {
      if (itr->second > 1) {
         cout << itr->first << " ";
         duplicate = true;
      }
   }
   if (duplicate == false)
   cout << "-1";
}
int main() {
   int arr[] = {12, 15, 12, 3, 6, 12, 3, 48, 56, 8, 48};
   int n = sizeof(arr) / sizeof(arr[0]);
   cout << "Duplicate elements are: ";
   displayDuplicates(arr, n);
}

Output

Duplicate elements are: 12 3 48
raja
Published on 18-Dec-2019 10:35:28
Advertisements