Difference between highest and least frequencies in an array - GeeksforGeeks

01 Jul, 2021
Given an array, find the difference between highest occurrence and least occurrence of any number in an arrayExamples:  
Input  : arr[] = [7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5]
Output : 2
Lowest occurring element (5) occurs once.
Highest occurring element (1 or 7) occurs 3 times

Input  : arr[] = [1, 1, 1, 3, 3, 3]
Output : 0
 
A simple solution is to use two loops to count frequency of every element and keep track of maximum and minimum frequencies.A better solution is to sort the array in O(n log n) and check consecutive element’s occurrence and compare their count respectively.  
C++
Java
Python3
C#
PHP
Javascript
// CPP code to find the difference between highest// and least frequencies#include <bits/stdc++.h>using namespace std; int findDiff(int arr[], int n){    // sort the array    sort(arr, arr + n);     int count = 0, max_count = 0, min_count = n;    for (int i = 0; i < (n - 1); i++) {         // checking consecutive elements        if (arr[i] == arr[i + 1]) {            count += 1;            continue;        }        else {            max_count = max(max_count, count);            min_count = min(min_count, count);            count = 0;        }    }     return (max_count - min_count);} // Driver codeint main(){    int arr[] = { 7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5 };    int n = sizeof(arr) / sizeof(arr[0]);     cout << findDiff(arr, n) << "\n";    return 0;}
// JAVA Code for Difference between// highest and least frequencies// in an arrayimport java.util.*; class GFG {     static int findDiff(int arr[], int n)    {        // sort the array        Arrays.sort(arr);         int count = 0, max_count = 0,            min_count = n;         for (int i = 0; i < (n - 1); i++) {             // checking consecutive elements            if (arr[i] == arr[i + 1]) {                count += 1;                continue;            }            else {                max_count = Math.max(max_count,                                     count);                 min_count = Math.min(min_count,                                     count);                count = 0;            }        }         return (max_count - min_count);    }     // Driver program to test above function    public static void main(String[] args)    {         int arr[] = { 7, 8, 4, 5, 4, 1,                      1, 7, 7, 2, 5 };        int n = arr.length;         System.out.println(findDiff(arr, n));    }} // This code is contributed by Arnav Kr. Mandal.
# Python3 code to find the difference# between highest nd least frequencies def findDiff(arr, n):         # sort the array    arr.sort()         count = 0; max_count = 0; min_count = n    for i in range(0, (n-1)):         # checking consecutive elements        if arr[i] == arr[i + 1]:            count += 1            continue        else:            max_count = max(max_count, count)            min_count = min(min_count, count)            count = 0    return max_count - min_count # Driver Codearr = [ 7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5 ]n = len(arr)print (findDiff(arr, n)) # This code is contributed by Shreyanshi Arun.
// C# Code for Difference between// highest and least frequencies// in an arrayusing System; class GFG {     static int findDiff(int[] arr, int n)    {                 // sort the array        Array.Sort(arr);         int count = 0, max_count = 0,            min_count = n;         for (int i = 0; i < (n - 1); i++) {             // checking consecutive elements            if (arr[i] == arr[i + 1]) {                count += 1;                continue;            }            else {                max_count = Math.Max(max_count,                                    count);                 min_count = Math.Min(min_count,                                    count);                count = 0;            }        }         return (max_count - min_count);    }     // Driver program to test above function    public static void Main()    {         int[] arr = { 7, 8, 4, 5, 4, 1,                       1, 7, 7, 2, 5 };        int n = arr.Length;         Console.WriteLine(findDiff(arr, n));    }} // This code is contributed by vt_m.
<?php// PHP code to find the// difference between highest// and least frequencies // function that// returns differencefunction findDiff($arr, $n){         // sort the array    sort($arr);     $count = 0; $max_count = 0;    $min_count = $n;    for ($i = 0; $i < ($n - 1); $i++)    {         // checking consecutive elements        if ($arr[$i] == $arr[$i + 1])        {            $count += 1;            continue;        }        else        {            $max_count = max($max_count, $count);            $min_count = min($min_count, $count);            $count = 0;        }    }     return ($max_count - $min_count);} // Driver Code$arr = array(7, 8, 4, 5, 4, 1,             1, 7, 7, 2, 5);$n = sizeof($arr); echo(findDiff($arr, $n) . "\n"); // This code is contributed by Ajit.?>
<script>    // Javascript Code for Difference between    // highest and least frequencies    // in an array         function findDiff(arr, n)    {                   // sort the array        arr.sort(function(a, b){return a - b});           let count = 0, max_count = 0, min_count = n;           for (let i = 0; i < (n - 1); i++) {               // checking consecutive elements            if (arr[i] == arr[i + 1]) {                count += 1;                continue;            }            else {                max_count = Math.max(max_count, count);                   min_count = Math.min(min_count, count);                count = 0;            }        }           return (max_count - min_count);    }         let arr = [ 7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5 ];    let n = arr.length;     document.write(findDiff(arr, n));         </script>
Output:  
 2
An efficient solution is to use hashing. We count frequencies of all elements and finally traverse the hash table to find maximum and minimum.Below is the implementation. 
C++
Java
Python3
C#
Javascript
// CPP code to find the difference between highest// and least frequencies#include <bits/stdc++.h>using namespace std; int findDiff(int arr[], int n){    // Put all elements in a hash map    unordered_map<int, int> hm;    for (int i = 0; i < n; i++)        hm[arr[i]]++;     // Find counts of maximum and minimum    // frequent elements    int max_count = 0, min_count = n;    for (auto x : hm) {        max_count = max(max_count, x.second);        min_count = min(min_count, x.second);    }     return (max_count - min_count);} // Driverint main(){    int arr[] = { 7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5 };    int n = sizeof(arr) / sizeof(arr[0]);     cout << findDiff(arr, n) << "\n";    return 0;}
// Java code to find the difference between highest// and least frequenciesimport java.util.*; class GFG{ static int findDiff(int arr[], int n){    // Put all elements in a hash map    Map<Integer,Integer> mp = new HashMap<>();    for (int i = 0 ; i < n; i++)    {        if(mp.containsKey(arr[i]))        {            mp.put(arr[i], mp.get(arr[i])+1);        }        else        {            mp.put(arr[i], 1);        }    }     // Find counts of maximum and minimum    // frequent elements    int max_count = 0, min_count = n;    for (Map.Entry<Integer,Integer> x : mp.entrySet())    {        max_count = Math.max(max_count, x.getValue());        min_count = Math.min(min_count, x.getValue());    }     return (max_count - min_count);} // Driver codepublic static void main(String[] args){    int arr[] = { 7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5 };    int n = arr.length;    System.out.println(findDiff(arr, n));}} /* This code is contributed by PrinciRaj1992 */
# Python code to find the difference between highest# and least frequencies from collections import defaultdictdef findDiff(arr,n):     # Put all elements in a hash map    mp = defaultdict(lambda:0)    for i in range(n):        mp[arr[i]]+=1     # Find counts of maximum and minimum    # frequent elements    max_count=0;min_count=n    for key,values in mp.items():        max_count= max(max_count,values)        min_count = min(min_count,values)     return max_count-min_count  # Driver codearr = [ 7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5]n = len(arr)print(findDiff(arr,n)) # This code is contributed by Shrikant13
// C# code to find the difference between highest// and least frequenciesusing System;using System.Collections.Generic; class GFG{ static int findDiff(int []arr, int n){    // Put all elements in a hash map    Dictionary<int,int> mp = new Dictionary<int,int>();    for (int i = 0 ; i < n; i++)    {        if(mp.ContainsKey(arr[i]))        {            var val = mp[arr[i]];            mp.Remove(arr[i]);            mp.Add(arr[i], val + 1);        }        else        {            mp.Add(arr[i], 1);        }    }     // Find counts of maximum and minimum    // frequent elements    int max_count = 0, min_count = n;    foreach(KeyValuePair<int, int> entry in mp)    {        max_count = Math.Max(max_count, entry.Value);        min_count = Math.Min(min_count, entry.Value);    }     return (max_count - min_count);} // Driver codepublic static void Main(String[] args){    int []arr = { 7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5 };    int n = arr.Length;    Console.WriteLine(findDiff(arr, n));}} // This code is contributed by Princi Singh
<script>      // JavaScript code to find the difference between highest      // and least frequencies      function findDiff(arr, n)      {               // Put all elements in a hash map        var mp = {};        for (var i = 0; i < n; i++) {          if (mp.hasOwnProperty(arr[i])) {            var val = mp[arr[i]];            delete mp[arr[i]];            mp[arr[i]] = val + 1;          } else {            mp[arr[i]] = 1;          }        }         // Find counts of maximum and minimum        // frequent elements        var max_count = 0,          min_count = n;        for (const [key, value] of Object.entries(mp)) {          max_count = Math.max(max_count, value);          min_count = Math.min(min_count, value);        }         return max_count - min_count;      }       // Driver code      var arr = [7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5];      var n = arr.length;      document.write(findDiff(arr, n));             // This code is contributed by rdtank.    </script>
Output:  
 2
Time Complexity : O(n)This article is contributed by Himanshu Ranjan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
vt_m
jit_t
shrikanth13
princiraj1992
princi singh
divyesh072019
rdtank
Arrays
Difference Between
Hash
Sorting
Arrays
Hash
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in Java
Introduction to Arrays
Maximum and minimum of an array using minimum number of comparisons
Python | Using 2D arrays/lists the right way
Linked List vs Array
Difference between BFS and DFS
Class method vs Static method in Python
Differences between TCP and UDP
Difference between Process and Thread
Difference between var, let and const keywords in JavaScript