Sunday, 12 November 2017

C++ Program to find the element occurring Odd number of times

Tags

C++ Program to find the element occurring Odd number of times is given below. Approach is simple we use the concept of hashing where element would be key and the its frequency (number of occurrence) will be value. Then we will check if the value to the key is odd or not.


PROGRAM:

#include <stdio.h>
#include <iostream>
#include <unordered_map>
using namespace std;
int main(){
    
    int n;
    cout<<"\nEnter the total number of elements: \n";
    cin>>n;

    int arr[n];
    std::unordered_map<int,int> m;
    cout<<"\n\nEnter the elements of the array: \n";
    for(int i=0;i<n;i++){
          cin>>arr[i];
          m[arr[i]]++;
    }
      
       cout<<"\nThe element occurring the odd number of times is: \n";
    for(auto it=m.begin();it!=m.end();it++){
         if(m[it->first]%2!=0){
          cout<<it->first;
          break;
         }
    }
    cout<<"\n";
    return 0;

}


OUTPUT:





EmoticonEmoticon