VOOZH about

URL: https://www.geeksforgeeks.org/cpp/cpp-program-to-count-dupicate-elements-in-an-array/

⇱ C++ Program to Count the Dupicate Elements in an Array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 23 Jul, 2025

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


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)



Comment