Find any one of the multiple repeating elements in read only array in C++


In this tutorial, we are going to write a program that finds the repeating element in the given array.

Let's see the steps to solve the problem.

  • Initialize the array.

  • Initialize a counter map to store the frequency of each element in the array.

  • Iterate over the array.

    • Count each element.

  • Print the element whose frequency is greater than 1.

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int findRepeatingElement(int arr[], int n) {
   map<int, int> frequencies;
   for (int i = 0; i < n; i++) {
      map<int, int>::iterator itr = frequencies.find(arr[i]);
      if (itr != frequencies.end()) {
         itr->second = itr->second + 1;
      }
      else {
         frequencies.insert({arr[i], 1});
      }
   }
   for (map<int, int>::iterator itr = frequencies.begin(); itr != frequencies.end(); ++itr) {
      if (itr->second > 1) {
         return itr->first;
      }
   }
}
int main() {
   int arr[] = {1, 2, 3, 3, 4, 5, 5, 6};
   cout << findRepeatingElement(arr, 8) << endl;
   return 0;
}

Output

If you run the above code, then you will get the following result

3

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

Updated on: 01-Feb-2021

60 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements