Find the element having different frequency than other array elements

Given an array of N integers. Each element in the array occurs same number of times except one element. The task is to find this element.

Examples:

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

Input : arr[] = {0, 1, 2, 4, 4}
Output : 4


The idea is to use a hash table freq to store the frequencies of given elements. Once we have frequencies in the hash table, we can traverse the table to find the only value which is different from others.

Below is the implementation of the above idea :

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find the element having
// different frequency than other array
// elements having same frequency
#include <bits/stdc++.h>
using namespace std;
  
// Function to find the element having
// different frequency from other array
// elements with same frequency
int findElement(int arr[], int n)
{
    // Store frequencies of elements
    unordered_map<int, int> freq;
    for (int i = 0; i < n; i++) {
  
        // increase the value by 1 for every
        // time the element occurs in an array
        freq[arr[i]]++;
    }
  
    // Below code is used find the only different
    // value in freq. 
    auto it = freq.begin();
    int fst_fre = it->second, fst_ele = it->first;
    if (freq.size() <= 2)
        return fst_fre;
    it++;
    int sec_fre = it->second, sec_ele = it->first;
    it++;
    int trd_fre = it->second, trd_ele = it->first;
    if (sec_fre == fst_fre && sec_fre != trd_fre)
        return trd_ele;
    if (sec_fre == trd_fre && sec_fre != fst_fre)
        return fst_ele;
    if (fst_fre == trd_fre && sec_fre != fst_fre)
        return sec_ele;
  
    // We reach here when first three frequencies are same
    it++;
    for (; it != freq.end(); it++) {
        if (it->second != fst_fre)
            return it->first;
    }
  
    return -1;
}
  
// Driver code
int main()
{
    int arr[] = { 0, 1, 2, 4, 4 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << findElement(arr, n) << endl;
    return 0;
}

chevron_right


Output:

4

Time Complexity : O(n)
Auxiliary Space : O(n)



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.