Skip to content
Related Articles

Related Articles

Least frequent element in an array

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 15 Nov, 2022
Improve Article
Save Article

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
Explanation: 3 appears minimum number of times in given array.

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

A simple solution is to run two loops. The outer loop picks all elements one by one. The inner loop finds frequency of the picked element and compares with the minimum so far.

C++




// CPP program to find the least frequent element in an
// array.
#include <bits/stdc++.h>
using namespace std;
 
int leastFrequent(int* arr, int n)
{
    int mincount = INT_MAX;
    int element_having_min_freq;
    for (int i = 0; i < n; i++) {
        int count = 0;
        for (int j = 0; j < n; j++) {
            if (arr[i] == arr[j])
                count++;
        }
 
        if (count < mincount) {
            mincount = count;
            element_having_min_freq = arr[i];
        }
    }
 
    return element_having_min_freq;
}
 
// 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;
}

Java




// Java program to find the least frequent element in an array.
import java.io.*;
 
public class Main {
 
  public static int INT_MAX = 1000000000;
  public static int leastFrequent(int arr[], int n) {
    int mincount = INT_MAX;
    int element_having_min_freq = -1;
    for (int i = 0; i < n; i++) {
      int count = 0;
      for (int j = 0; j < n; j++) {
        if (arr[i] == arr[j])
          count++;
      }
 
      if (count < mincount) {
        mincount = count;
        element_having_min_freq = arr[i];
      }
    }
 
    return element_having_min_freq;
  }
 
  // Driver program
  public static void main(String[] args) {
    int arr[] = { 1, 3, 2, 1, 2, 2, 3, 1 };
    int n = 8;
    System.out.println(leastFrequent(arr, n));
  }
}
 
// This code is contributed by ajaymakvana.

Python3




class Main :
    INT_MAX = 1000000000
    @staticmethod
    def  leastFrequent( arr,  n) :
        mincount = Main.INT_MAX
        element_having_min_freq = -1
        i = 0
        while (i < n) :
            count = 0
            j = 0
            while (j < n) :
                if (arr[i] == arr[j]) :
                    count += 1
                j += 1
            if (count < mincount) :
                mincount = count
                element_having_min_freq = arr[i]
            i += 1
        return element_having_min_freq
    # Driver program
    @staticmethod
    def main( args) :
        arr = [1, 3, 2, 1, 2, 2, 3, 1]
        n = 8
        print(Main.leastFrequent(arr, n))
     
if __name__=="__main__":
    Main.main([])
     
    # This code is contributed by aadityaburujwale.

C#




// C# program to find the least frequent element in an array.
using System;
 
public class GFG {
  public static int INT_MAX = 1000000000;
  public static int leastFrequent(int[] arr, int n) {
    int mincount = INT_MAX;
    int element_having_min_freq = -1;
    for (int i = 0; i < n; i++) {
      int count = 0;
      for (int j = 0; j < n; j++) {
        if (arr[i] == arr[j])
          count++;
      }
 
      if (count < mincount) {
        mincount = count;
        element_having_min_freq = arr[i];
      }
    }
 
    return element_having_min_freq;
  }
 
  // Driver program
  public static void Main(string[] args) {
    int[] arr = { 1, 3, 2, 1, 2, 2, 3, 1 };
    int n = 8;
    Console.WriteLine(leastFrequent(arr, n));
  }
}
 
// This code is contributed by ajaymakavana.

Javascript




function leastFrequent(arr, n)
{
    let mincount = Number.MAX_VALUE;
    let element_having_min_freq;
    for (let i = 0; i < n; i++) {
        let count = 0;
        for (let j = 0; j < n; j++) {
            if (arr[i] == arr[j])
                count++;
        }
 
        if (count < mincount) {
            mincount = count;
            element_having_min_freq = arr[i];
        }
    }
 
    return element_having_min_freq;
}
 
// Driver program
    let arr = [ 1, 3, 2, 1, 2, 2, 3, 1 ];
    let n = 8;
    console.log(leastFrequent(arr, n));
     
    // This code is contributed by garg28harsh.

Output

3

Time Complexity: O(n2)
Auxiliary Space: O(1)

A better solution is to do sorting. We first sort the array, then linearly traverse the array.

Implementation:

C++




// CPP program to find the least frequent element
// in an array.
#include <bits/stdc++.h>
using namespace std;
 
int leastFrequent(int arr[], int n)
{
    // Sort the array
    sort(arr, arr + n);
 
    // find the min frequency using linear traversal
    int min_count = n + 1, res = -1, curr_count = 1;
    for (int i = 1; i < n; i++) {
        if (arr[i] == arr[i - 1])
            curr_count++;
        else {
            if (curr_count < min_count) {
                min_count = curr_count;
                res = arr[i - 1];
            }
            curr_count = 1;
        }
    }
 
    // If last element is least frequent
    if (curr_count < min_count) {
        min_count = curr_count;
        res = arr[n - 1];
    }
 
    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;
}

Java




// Java program to find the least frequent element
// in an array.
import java.io.*;
import java.util.*;
 
class GFG {
 
    static int leastFrequent(int arr[], int n)
    {
 
        // Sort the array
        Arrays.sort(arr);
 
        // find the min frequency using
        // linear traversal
        int min_count = n + 1, res = -1;
        int curr_count = 1;
 
        for (int i = 1; i < n; i++) {
            if (arr[i] == arr[i - 1])
                curr_count++;
            else {
                if (curr_count < min_count) {
                    min_count = curr_count;
                    res = arr[i - 1];
                }
 
                curr_count = 1;
            }
        }
 
        // If last element is least frequent
        if (curr_count < min_count) {
            min_count = curr_count;
            res = arr[n - 1];
        }
 
        return res;
    }
 
    // driver program
    public static void main(String args[])
    {
        int arr[] = { 1, 3, 2, 1, 2, 2, 3, 1 };
        int n = arr.length;
        System.out.print(leastFrequent(arr, n));
    }
}
 
/*This code is contributed by Nikita Tiwari.*/

Python3




# Python 3 program to find the least
# frequent element in an array.
 
 
def leastFrequent(arr, n):
 
    # Sort the array
    arr.sort()
 
    # find the min frequency using
    # linear traversal
    min_count = n + 1
    res = -1
    curr_count = 1
    for i in range(1, n):
        if (arr[i] == arr[i - 1]):
            curr_count = curr_count + 1
        else:
            if (curr_count < min_count):
                min_count = curr_count
                res = arr[i - 1]
 
            curr_count = 1
 
    # If last element is least frequent
    if (curr_count < min_count):
        min_count = curr_count
        res = arr[n - 1]
 
    return res
 
 
# Driver program
arr = [1, 3, 2, 1, 2, 2, 3, 1]
n = len(arr)
print(leastFrequent(arr, n))
 
 
# This code is contributed
# by Nikita Tiwari.

C#




// C# program to find the least
// frequent element in an array.
using System;
 
class GFG {
 
    static int leastFrequent(int[] arr, int n)
    {
        // Sort the array
        Array.Sort(arr);
 
        // find the min frequency
        // using linear traversal
        int min_count = n + 1, res = -1;
        int curr_count = 1;
 
        for (int i = 1; i < n; i++) {
            if (arr[i] == arr[i - 1])
                curr_count++;
            else {
                if (curr_count < min_count) {
                    min_count = curr_count;
                    res = arr[i - 1];
                }
 
                curr_count = 1;
            }
        }
 
        // If last element is least frequent
        if (curr_count < min_count) {
            min_count = curr_count;
            res = arr[n - 1];
        }
 
        return res;
    }
 
    // Driver code
    static public void Main()
    {
        int[] arr = { 1, 3, 2, 1, 2, 2, 3, 1 };
        int n = arr.Length;
 
        // Function calling
        Console.Write(leastFrequent(arr, n));
    }
}
 
// This code is contributed by Shrikant13

PHP




<?php
// PHP program to find the
// least frequent element
// in an array.
 
function leastFrequent($arr, $n)
{
     
    // Sort the array
    sort($arr);
    sort($arr , $n);
 
    // find the min frequency
    // using linear traversal
    $min_count = $n + 1;
    $res = -1;
    $curr_count = 1;
    for($i = 1; $i < $n; $i++)
    {
        if ($arr[$i] == $arr[$i - 1])
            $curr_count++;
        else
        {
            if ($curr_count < $min_count)
            {
                $min_count = $curr_count;
                $res = $arr[$i - 1];
            }
            $curr_count = 1;
        }
    }
 
    // If last element is
    // least frequent
    if ($curr_count < $min_count)
    {
        $min_count = $curr_count;
        $res = $arr[$n - 1];
    }
 
    return $res;
}
 
// Driver Code
{
    $arr = array(1, 3, 2, 1, 2, 2, 3, 1);
    $n = sizeof($arr) / sizeof($arr[0]);
    echo leastFrequent($arr, $n);
    return 0;
}
 
// This code is contributed by nitin mittal
?>

Javascript




<script>
 
// JavaScript program to find the least frequent element
// in an array.
 
    function leastFrequent(arr, n)
    {
           
        // Sort the array
        arr.sort();
       
        // find the min frequency using
        // linear traversal
        let min_count = n+1, res = -1;
        let curr_count = 1;
           
        for (let i = 1; i < n; i++) {
            if (arr[i] == arr[i - 1])
                curr_count++;
            else {
                if (curr_count < min_count) {
                    min_count = curr_count;
                    res = arr[i - 1];
                }
                   
                curr_count = 1;
            }
        }
       
        // If last element is least frequent
        if (curr_count < min_count)
        {
            min_count = curr_count;
            res = arr[n - 1];
        }
       
        return res;
    }
 
// Driver code
 
        let arr = [1, 3, 2, 1, 2, 2, 3, 1];
        let n = arr.length;
        document.write(leastFrequent(arr, n));
                                
</script>

Output

3

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

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.

Implementation:

C++




// 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;
}

Java




// Java program to find the least frequent element
// in an array
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
 
class GFG {
 
    static int leastFrequent(int arr[], int n)
    {
 
        // Insert all elements in hash.
        Map<Integer, Integer> count
            = new HashMap<Integer, Integer>();
 
        for (int i = 0; i < n; i++) {
            int key = arr[i];
            if (count.containsKey(key)) {
                int freq = count.get(key);
                freq++;
                count.put(key, freq);
            }
            else
                count.put(key, 1);
        }
 
        // find min frequency.
        int min_count = n + 1, res = -1;
        for (Entry<Integer, Integer> val :
             count.entrySet()) {
            if (min_count >= val.getValue()) {
                res = val.getKey();
                min_count = val.getValue();
            }
        }
 
        return res;
    }
 
    // driver program
    public static void main(String[] args)
    {
 
        int arr[] = { 1, 3, 2, 1, 2, 2, 3, 1 };
        int n = arr.length;
 
        System.out.println(leastFrequent(arr, n));
    }
}
 
// This code is contributed by Akash Singh.

Python3




# Python3 program to find the most
# frequent element in an array.
import math as mt
 
 
def leastFrequent(arr, n):
 
    # Insert all elements in Hash.
    Hash = dict()
    for i in range(n):
        if arr[i] in Hash.keys():
            Hash[arr[i]] += 1
        else:
            Hash[arr[i]] = 1
 
    # find the max frequency
    min_count = n + 1
    res = -1
    for i in Hash:
        if (min_count >= Hash[i]):
            res = i
            min_count = Hash[i]
 
    return res
 
 
# Driver Code
arr = [1, 3, 2, 1, 2, 2, 3, 1]
n = len(arr)
print(leastFrequent(arr, n))
 
# This code is contributed by
# mohit kumar 29

C#




// C# program to find the
// least frequent element
// in an array.
using System;
using System.Collections.Generic;
 
class GFG {
    static int leastFrequent(int[] arr, int n)
    {
        // Insert all elements in hash.
        Dictionary<int, int> count
            = new Dictionary<int, int>();
        for (int i = 0; i < n; i++) {
            int key = arr[i];
            if (count.ContainsKey(key)) {
                int freq = count[key];
                freq++;
                count[key] = freq;
            }
            else
                count.Add(key, 1);
        }
 
        // find the min frequency
        int min_count = n + 1, res = -1;
        foreach(KeyValuePair<int, int> pair in count)
        {
            if (min_count >= pair.Value) {
                res = pair.Key;
                min_count = pair.Value;
            }
        }
        return res;
    }
 
    // Driver Code
    static void Main()
    {
        int[] arr = new int[] { 1, 3, 2, 1, 2, 2, 3, 1 };
        int n = arr.Length;
        Console.Write(leastFrequent(arr, n));
    }
}
 
// This code is contributed by
// Manish Shaw(manishshaw1)

Javascript




<script>
 
// JavaScript program to find the least frequent element
// in an array.
 
function leastFrequent(arr, n)
{
    // Insert all elements in hash.
    var hash = new Map();
    for (var i = 0; i < n; i++)
    {
        if(hash.has(arr[i]))
            hash.set(arr[i], hash.get(arr[i])+1)
        else
            hash.set(arr[i], 1);
    }
 
    // find the min frequency
    var min_count = n+1, res = -1;
 
    hash.forEach((value, key) => {
         
        if (min_count >= value) {
            res = key;
            min_count = value;
        }
    });
 
    return res;
}
 
// driver program
var arr = [1, 3, 2, 1, 2, 2, 3, 1];
var n = arr.length;
document.write( leastFrequent(arr, n));
 
</script>

Output

3

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


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!