Difference between highest and least frequencies in an array
Last Updated :
06 Nov, 2023
Given an array, find the difference between highest occurrence and least occurrence of any number in an array
Examples:
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 the frequency of every element and keep track of maximum and minimum frequencies.
Algorithm:
- Define function named maxMinDiff with two parameters arr[] and n.
- Initialize variables maxFreq to INT_MIN and minFreq to INT_MAX.
- Loop through array arr[] from i = 0 to n-1
- Initialize count variable to 0
- Loop through array arr[] from j = 0 to n-1
- If arr[i] is equal to arr[j], increment count
- Update maxFreq and minFreq with maximum and minimum of their respective values and count
- Find difference between maxFreq and minFreq and store it in variable diff
- Return diff
Below is the implementation of the approach:
C++
// C++ code for the approach
#include<bits/stdc++.h>
using namespace std;
// function that
// returns difference
int maxMinDiff(int arr[], int n) {
// Initializing variables
int maxFreq = INT_MIN, minFreq = INT_MAX;
// Loop to count the frequency of every element
for(int i=0; i<n; i++) {
int count = 0;
for(int j=0; j<n; j++) {
if(arr[i] == arr[j])
count++;
}
// Updating maximum and minimum frequencies
maxFreq = max(maxFreq, count);
minFreq = min(minFreq, count);
}
// Finding the difference between maximum and minimum frequencies
return (maxFreq - minFreq);
}
// Driver code
int main() {
int arr[] = { 7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5 };
int n = sizeof(arr)/sizeof(arr[0]);
// Function call
int diff = maxMinDiff(arr, n);
cout << diff << endl;
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class Main {
// Function that returns difference
public static int maxMinDiff(int[] arr, int n)
{
// Initializing variables
int maxFreq = Integer.MIN_VALUE,
minFreq = Integer.MAX_VALUE;
// Loop to count the frequency
// of every element
for (int i = 0; i < n; i++) {
int count = 0;
for (int j = 0; j < n; j++) {
if (arr[i] == arr[j])
count++;
}
// Updating the maximum and
// minimum frequencies
maxFreq = Math.max(maxFreq, count);
minFreq = Math.min(minFreq, count);
}
// Finding the difference between maximum
// and minimum frequencies
return (maxFreq - minFreq);
}
// Driver Code
public static void main(String[] args)
{
int arr[] = { 7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5 };
int n = arr.length;
int diff = maxMinDiff(arr, n);
System.out.println(diff);
}
}
Python
def max_min_diff(arr):
# Initializing variables
max_freq = float('-inf')
min_freq = float('inf')
# Loop to count the frequency of every element
for i in range(len(arr)):
count = 0
for j in range(len(arr)):
if arr[i] == arr[j]:
count += 1
# Updating maximum and minimum frequencies
max_freq = max(max_freq, count)
min_freq = min(min_freq, count)
# Finding the difference between maximum and minimum frequencies
return max_freq - min_freq
# Driver code
if __name__ == "__main__":
arr = [7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5]
# Function call
diff = max_min_diff(arr)
print(diff)
C#
using System;
class Program
{
// Function that returns the difference between the maximum and minimum frequencies
static int MaxMinDiff(int[] arr, int n)
{
// Initializing variables for maximum and minimum frequencies
int maxFreq = int.MinValue;
int minFreq = int.MaxValue;
// Loop to count the frequency of every element
for (int i = 0; i < n; i++)
{
int count = 0;
for (int j = 0; j < n; j++)
{
if (arr[i] == arr[j])
count++;
}
// Updating maximum and minimum frequencies
maxFreq = Math.Max(maxFreq, count);
minFreq = Math.Min(minFreq, count);
}
// Finding the difference between maximum and minimum frequencies
return maxFreq - minFreq;
}
// Driver code
static void Main()
{
int[] arr = { 7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5 };
int n = arr.Length;
// Function call
int diff = MaxMinDiff(arr, n);
Console.WriteLine(diff);
}
}
JavaScript
// Function that returns the difference between the maximum and minimum
// frequencies of elements in an array
function maxMinDiff(arr) {
// Initializing variables
let maxFreq = -Infinity;
let minFreq = Infinity;
// Loop to count the frequency of every element
for (let i = 0; i < arr.length; i++) {
let count = 0;
for (let j = 0; j < arr.length; j++) {
if (arr[i] === arr[j]) {
count++;
}
}
// Updating maximum and minimum frequencies
maxFreq = Math.max(maxFreq, count);
minFreq = Math.min(minFreq, count);
}
// Finding the difference between maximum and minimum frequencies
return maxFreq - minFreq;
}
// Driver code
const arr = [7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5];
const diff = maxMinDiff(arr);
console.log(diff);
Time Complexity: O(N*N) where N is the size of input array. This is because two nested for loops are executing in maxMinDiff function.
Space Complexity: O(1) as no extra space has been taken.
A better solution is to sort the array in O(n log n) and check consecutive element's occurrence and compare their count respectively.
Implementation:
C++
// 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 code
int 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
// JAVA Code for Difference between
// highest and least frequencies
// in an array
import 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
# 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 Code
arr = [ 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#
// C# Code for Difference between
// highest and least frequencies
// in an array
using 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.
JavaScript
<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>
PHP
<?php
// PHP code to find the
// difference between highest
// and least frequencies
// function that
// returns difference
function 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.
?>
Time Complexity: O(nlogn) the inbuilt sort function takes N log N time to complete all operations, hence the overall time taken by the algorithm is N log N
Space Complexity: O(1) since no extra array is used so the space taken by the algorithm is constant
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++
// 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);
}
// Driver
int 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
// Java code to find the difference between highest
// and least frequencies
import 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 code
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 PrinciRaj1992 */
Python3
# Python code to find the difference between highest
# and least frequencies
from collections import defaultdict
def 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 code
arr = [ 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#
// C# code to find the difference between highest
// and least frequencies
using 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 code
public 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
JavaScript
<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>
Time Complexity: O(n) since one traversal of the array is required to complete all operations hence the overall time required by the algorithm is linear
Auxiliary Space: O(n) since an unordered map is used, in the worst case all elements will be stored inside the unordered map thus the space taken by the algorithm is linear
This article is contributed by Himanshu Ranjan.
Similar Reads
Maximum difference between first and last indexes of an element in array
Given an array of n integers. The task is to find the difference of first and last index of each distinct element so as to maximize the difference. Examples: Input : {2, 1, 3, 4, 2, 1, 5, 1, 7} Output : 6 Element 1 has its first index = 1 and last index = 7 Difference = 7 - 1 = 6 Other elements have
6 min read
Maximum difference between two elements in an Array
Given an array arr[] of N integers, the task is to find the maximum difference between any two elements of the array.Examples: Input: arr[] = {2, 1, 5, 3} Output: 4 |5 - 1| = 4 Input: arr[] = {-10, 4, -9, -5} Output: 14 Naive Approach:- As the maximum difference will be in between smallest and the l
9 min read
Find element with highest frequency in given nested Array
Given an array arr[] of N integers. The task is to create a frequency array freq[] of the given array arr[] and find the maximum element of the frequency array. If two elements have the same frequency in the array freq[], then return the element which has a smaller value. Examples: Input: arr[] = {1
8 min read
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 : 3Explanation: 3 appears minimum number of times in given array. Input : arr[] = {10, 20, 30}Outp
12 min read
Maximum absolute difference between distinct elements in an Array
Given an array arr[] of N integers, the task is to find the maximum absolute difference between distinct elements of the array.Examples: Input: arr[] = {12, 10, 9, 45, 2, 10, 10, 45, 10} Output: 10 Explanation: Distinct elements of given array are 12, 9, 2. Therefore, the maximum absolute difference
7 min read
Minimum distance between any most frequent and least frequent element of an array
Given an integer array arr[] of size N, the task is to find the minimum distance between any most and least frequent element of the given array. Examples: Input: arr[] = {1, 1, 2, 3, 2, 3, 3}Output: 1Explanation: The least frequent elements are 1 and 2 which occurs at indexes: 0, 1, 2, 4. Whereas, t
13 min read
Maximum difference between group of k-elements and rest of the array.
You are given an array of n elements. You have to divide the given array into two group such that one group consists exactly k elements and second group consists rest of elements. Your result must be maximum possible difference of sum of elements of these two group. Examples: Input : arr[n] = {1, 5,
7 min read
Generate N sized Array with mean K and minimum difference between min and max
Given two integers N and X, the task is to find an output array arr[] containing distinct integers of length N such that their average is K and the difference between the minimum and the maximum is minimum possible. Input: N = 4, X = 8Output :- 6 7 9 10Explanation: Clearly the mean of 6, 7, 9, 10 is
6 min read
Find minimum difference between any two elements | Set 2
Given an unsorted array arr[] of size n, the task is to find the minimum difference between any pair in the given array. Input: arr[] = {1, 2, 3, 4} Output: 1 The possible absolute differences are: {1, 2, 3, 1, 2, 1}Input: arr[] = {10, 2, 5, 4} Output: 1 Approach: Traverse through the array and crea
8 min read
Minimum distance between peak elements in a given array
Given an array arr[], the task is to find the minimum distance between the two peak elements in the given array. Examples: Input: arr[] = {2, 3, 1, 2, 4, 1, 2}Output: 2Explanation: The peak elements in the given array are {2, 3, 1, 2, 4, 1, 2}. Hence the distance between 4 and 2 is (6 - 4) = 2 which
6 min read