
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
#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.
Advertisements