Open In App

C++ Program to Count the Dupicate Elements in an Array

Last Updated : 04 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, an array is a data structure that is used to store multiple values of similar data types in a contiguous memory location. In this article, we will learn how to count the duplicate elements in an array in C++.

Examples:

Input:
myArray = {1, 2, 2, 3, 3, 3};

Output:
Number of Duplicates: 3

Find the Number of Duplicate Elements in an Array in C++

To count the duplicate elements in an array in C++, we can use a std::set container which only stores the unique elements. We can store the array elements in the set while traversing the array and if the element is already present, then it means that the current element is duplicate.

Approach

Inside the function, initialize a set to store the unique elements from the array, and an integer to keep track of the count of duplicate elements.

  • Traverse the array using a loop. For each element in the array, do the following:
  • Use the std::set::find() function of the set to check if the current element is already in the set.
  • If the element is in the set, it means it’s a duplicate. So, increment the count of duplicate elements.
  • If the element is not in the set, it means it’s the first time we’re seeing this element. So, insert it into the set.
  • After the loop, return the count of duplicate elements.

C++ Program to Count the Duplicate Elements in an Array

C++




// C++ Program to illustrate how to Find the Number of
// Duplicate Elements in an Array
#include <iostream>
#include <set>
#include <vector>
using namespace std;
  
int countDuplicates(int* arr, int n)
{
    // Set to store unique elements
    set<int> uniqueSet;
    // Counter for duplicate elements
    int duplicateCount = 0;
  
    for (int i = 0; i < n; i++) {
        if (uniqueSet.find(arr[i]) != uniqueSet.end()) {
            // If element is already present in the set,
            // increment duplicate count
            duplicateCount++;
        }
        else {
            // If element is not present in the set, add it
            // to the set
            uniqueSet.insert(arr[i]);
        }
    }
  
    return duplicateCount;
}
  
// Driver code
int main()
{
    // Input array
    int arr[] = { 12, 11, 40, 12, 5, 6, 5, 12, 11 };
    int n = sizeof(arr) / sizeof(arr[0]);
  
    int duplicates = countDuplicates(arr, n);
  
    cout << "Number of Duplicate elements are "
         << duplicates;
    return 0;
}


Output

Number of Duplicate elements are 4

Time Complexity: O(N log N), where N is the size of the array.
Auxiliary Space: O(N)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads