First element that appears even number of times in an array in C++

C++Server Side ProgrammingProgramming

In this problem, we are given an array arr[] consisting of N integer values. Our task is to create a program for finding the first element that appears even number of times in an array. If any element exists that satisfies the condition return it otherwise return -1 denoting false.

Let's take an example to understand the problem,

Input: arr[] = {2, 3, 7, 2, 3, 6, 4, 1, 2}
Output: 3

Solution Approach

A simple method to solve the problem is by considering each element of the array one by one and then checking the element's occurrence frequency even and returning the first element in the array with even occurrence frequency. Another method to solve the problem is by using hash map data structure. For this, we will traverse the array and create a hash map that store the elements along with their occurrence frequency as toggle i.e. true or false based on the fact that it is even or not. This will reduce the overheads of checking whether the occurrence frequency is true or false as the toggle will show the required result. For the map, the first element whose values are true (denoting even frequency of occurrence) is our required result.

We will traverse the array and for each value, in the array i.e. arr[i] we will check in the map,

If it is not present in the map, add it to the map with the toggle value 'false'. If it is present in the map, toggle the current value corresponding to it i.e. if it is 'true' make it 'false', and if it is 'false' make it 'true'.

After the iteration of the array, iterate the map and return the first value with a corresponding value of toggle as 'true'.

Example

Program to illustrate the working of our solution

#include <bits/stdc++.h>
using namespace std;
int findFirstEvenFreqVal(int arr[], int n){
   unordered_map<int, bool> freqTogMap;
   for (int i = 0; i < n; i++){
      if (freqTogMap.find(arr[i]) == freqTogMap.end())
         freqTogMap.insert(pair <int,bool> (arr[i],false));
      else
      {
         bool val = freqTogMap.find(arr[i])->second;
         if (val == true)
            freqTogMap.find(arr[i])->second = false;
         else
            freqTogMap.find(arr[i])->second = true;
      }
   }
   int j = 0;
   for (j = 0; j < n; j++){
      if (freqTogMap.find(arr[j])->second == true)
         return arr[j];;
   }
   return -1;
}
int main(){
   int arr[] = { 2, 4, 6, 8, 1, 6 };
   cout<<"The first element of the array which appears even number of times is "  <<findFirstEvenFreqVal(arr, 6);
   return 0;
}

Output

The first element of the array which appears even number of times is 6
raja
Updated on 01-Feb-2022 07:22:24

Advertisements