Least frequent element in an array

Given an array, find the least frequent element in it. If there are multiple elements that appear least number of times, print any one of them.

Examples :

Input : arr[] = {1, 3, 2, 1, 2, 2, 3, 1}
Output : 3
3 appears minimum number of times in given
array.

Input : arr[] = {10, 20, 30} 

Output : 10 or 20 or 30 


An efficient solution is to use hashing. We create a hash table and store elements and their frequency counts as key value pairs. Finally we traverse the hash table and print the key with minimum value.


// CPP program to find the least frequent element
// in an array.
#include <bits/stdc++.h>
using namespace std;
  
int leastFrequent(int arr[], int n)
{
    // Insert all elements in hash.
    unordered_map<int, int> hash;
    for (int i = 0; i < n; i++)
        hash[arr[i]]++;
  
    // find the min frequency
    int min_count = n+1, res = -1;
    for (auto i : hash) {
        if (min_count >= i.second) {
            res = i.first;
            min_count = i.second;
        }
    }
  
    return res;
}
  
// driver program
int main()
{
    int arr[] = {1, 3, 2, 1, 2, 2, 3, 1};
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << leastFrequent(arr, n);
    return 0;
}
Output:
3

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

































































Comments

Popular posts from this blog

[13 Feb 2020] Check if a given sequence of moves for a robot is circular or not

[1] C++ Interview Questions