Check if frequency of each element in given array is unique or not
Last Updated :
20 Sep, 2023
Given an array arr[] of N positive integers where the integers are in the range from 1 to N, the task is to check whether the frequency of the elements in the array is unique or not. If all the frequency is unique then print “Yes”, else print “No”.
Examples:
Input: N = 5, arr[] = {1, 1, 2, 5, 5}
Output: No
Explanation:
The array contains 2 (1’s), 1 (2’s) and 2 (5’s), since the number of frequency of 1 and 5 are the same i.e. 2 times. Therefore, this array does not satisfy the condition.
Input: N = 10, arr[] = {2, 2, 5, 10, 1, 2, 10, 5, 10, 2}
Output: Yes
Explanation:
Number of 1’s -> 1
Number of 2’s -> 4
Number of 5’s -> 2
Number of 10’s -> 3.
Since, the number of occurrences of elements present in the array is unique. Therefore, this array satisfy the condition.
Naive Approach: The idea is to check for every number from 1 to N whether it is present in the array or not. If yes, then count the frequency of that element in the array, and store the frequency in an array. At last, just check for any duplicate element in the array and print the output accordingly.
- Iterate over every number in the range from 1 to N
- Counting the frequency of each element in frequency[] array
- Iterate over the frequency array
- Checking if the frequency[] array contains any duplicates or not
- If any duplicate frequency is found then return false.
- If no duplicate frequency is found, then return true
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool checkUniqueFrequency( int arr[], int n)
{
vector< int > frequency(n + 1);
for ( int i = 1; i <= n; i++) {
for ( int j = 0; j < n; j++) {
if (arr[j] == i) {
frequency[i - 1]++;
}
}
}
for ( int i = 0; i < n; i++) {
for ( int j = 0; j < n; j++) {
if (i == j || frequency[i] == 0)
continue ;
if (frequency[i] == frequency[j]) {
return false ;
}
}
}
return true ;
}
int main()
{
int arr[] = { 2, 2, 5, 10, 1, 2, 10, 5, 10, 2 };
int n = sizeof arr / sizeof arr[0];
bool res = checkUniqueFrequency(arr, n);
if (res)
cout << "Yes" << endl;
else
cout << "No" << endl;
return 0;
}
|
Java
import java.io.*;
class GFG {
static boolean checkUniqueFrequency( int arr[], int n)
{
int [] frequency = new int [n + 1 ];
for ( int i = 1 ; i <= n; i++) {
for ( int j = 0 ; j < n; j++) {
if (arr[j] == i) {
frequency[i - 1 ]++;
}
}
}
for ( int i = 0 ; i < n; i++) {
for ( int j = 0 ; j < n; j++) {
if (i == j || frequency[i] == 0 )
continue ;
if (frequency[i] == frequency[j]) {
return false ;
}
}
}
return true ;
}
public static void main (String[] args) {
int arr[] = { 2 , 2 , 5 , 10 , 1 , 2 , 10 , 5 , 10 , 2 };
int n = arr.length;
boolean res = checkUniqueFrequency(arr, n);
if (res)
System.out.println( "Yes" );
else
System.out.println( "No" );
}
}
|
Python3
def checkUniqueFrequency(arr, n):
frequency = [ 0 ] * (n + 1 );
for i in range ( 1 ,n + 1 ):
for j in range ( 0 ,n):
if (arr[j] = = i):
frequency[i - 1 ] + = 1 ;
for i in range ( 0 , n):
for j in range ( 0 , n):
if (i = = j or frequency[i] = = 0 ):
continue ;
if (frequency[i] = = frequency[j]):
return False ;
return True ;
arr = [ 2 , 2 , 5 , 10 , 1 , 2 , 10 , 5 , 10 , 2 ];
n = len (arr);
res = checkUniqueFrequency(arr, n);
if (res):
print ( "Yes" );
else :
print ( "No" );
|
C#
using System;
public class GFG {
static bool CheckUniqueFrequency( int [] arr, int n)
{
int [] frequency = new int [n + 1];
for ( int i = 1; i <= n; i++) {
for ( int j = 0; j < n; j++) {
if (arr[j] == i) {
frequency[i - 1]++;
}
}
}
for ( int i = 0; i < n; i++) {
for ( int j = 0; j < n; j++) {
if (i == j || frequency[i] == 0)
continue ;
if (frequency[i] == frequency[j]) {
return false ;
}
}
}
return true ;
}
static void Main( string [] args)
{
int [] arr = { 2, 2, 5, 10, 1, 2, 10, 5, 10, 2 };
int n = arr.Length;
bool res = CheckUniqueFrequency(arr, n);
if (res)
Console.WriteLine( "Yes" );
else
Console.WriteLine( "No" );
}
}
|
Javascript
<script>
function checkUniqueFrequency(arr, n)
{
var frequency = Array(n + 1).fill(0);
for ( var i = 1; i <= n; i++)
{
for ( var j = 0; j < n; j++)
{
if (arr[j] == i)
{
frequency[i - 1]++;
}
}
}
for ( var i = 0; i < n; i++)
{
for ( var j = 0; j < n; j++)
{
if (i == j || frequency[i] == 0)
{
continue ;
}
if (frequency[i] == frequency[j])
{
return false ;
}
}
}
return true ;
}
let arr = [ 2, 2, 5, 10, 1, 2, 10, 5, 10, 2 ];
let n = arr.length;
let res = checkUniqueFrequency(arr, n);
if (res)
document.write( "Yes" );
else
document.write( "No" );
</script>
|
Time Complexity: O(N2)
Auxiliary Space: O(N)
Efficient Approach: The idea is to use Hashing. Below are the steps:
- Traverse the given array arr[] and store the frequency of each element in a Map.
- Now traverse the map and check if the count of any element occurred more than once.
- If the count of any element in the above steps is more than one then print “No”, else print “Yes”.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool checkUniqueFrequency( int arr[],
int n)
{
unordered_map< int , int > freq;
for ( int i = 0; i < n; i++) {
freq[arr[i]]++;
}
unordered_set< int > uniqueFreq;
for ( auto & i : freq) {
if (uniqueFreq.count(i.second))
return false ;
else
uniqueFreq.insert(i.second);
}
return true ;
}
int main()
{
int arr[] = { 1, 1, 2, 5, 5 };
int n = sizeof arr / sizeof arr[0];
bool res = checkUniqueFrequency(arr, n);
if (res)
cout << "Yes" << endl;
else
cout << "No" << endl;
return 0;
}
|
Java
import java.util.*;
class GFG{
static boolean checkUniqueFrequency( int arr[],
int n)
{
HashMap<Integer,
Integer> freq = new HashMap<Integer,
Integer>();
for ( int i = 0 ; i < n; i++)
{
if (freq.containsKey(arr[i]))
{
freq.put(arr[i], freq.get(arr[i]) + 1 );
} else
{
freq.put(arr[i], 1 );
}
}
HashSet<Integer> uniqueFreq = new HashSet<Integer>();
for (Map.Entry<Integer,
Integer> i : freq.entrySet())
{
if (uniqueFreq.contains(i.getValue()))
return false ;
else
uniqueFreq.add(i.getValue());
}
return true ;
}
public static void main(String[] args)
{
int arr[] = { 1 , 1 , 2 , 5 , 5 };
int n = arr.length;
boolean res = checkUniqueFrequency(arr, n);
if (res)
System.out.print( "Yes" + "\n" );
else
System.out.print( "No" + "\n" );
}
}
|
Python3
from collections import defaultdict
def checkUniqueFrequency(arr, n):
freq = defaultdict ( int )
for i in range (n):
freq[arr[i]] + = 1
uniqueFreq = set ([])
for i in freq:
if (freq[i] in uniqueFreq):
return False
else :
uniqueFreq.add(freq[i])
return True
if __name__ = = "__main__" :
arr = [ 1 , 1 , 2 , 5 , 5 ]
n = len (arr)
res = checkUniqueFrequency(arr, n)
if (res):
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
using System.Collections.Generic;
class GFG{
static bool checkUniqueFrequency( int []arr,
int n)
{
Dictionary< int ,
int > freq = new Dictionary< int ,
int >();
for ( int i = 0; i < n; i++)
{
if (freq.ContainsKey(arr[i]))
{
freq[arr[i]] = freq[arr[i]] + 1;
} else
{
freq.Add(arr[i], 1);
}
}
HashSet< int > uniqueFreq = new HashSet< int >();
foreach (KeyValuePair< int ,
int > i in freq)
{
if (uniqueFreq.Contains(i.Value))
return false ;
else
uniqueFreq.Add(i.Value);
}
return true ;
}
public static void Main(String[] args)
{
int []arr = { 1, 1, 2, 5, 5 };
int n = arr.Length;
bool res = checkUniqueFrequency(arr, n);
if (res)
Console.Write( "Yes" + "\n" );
else
Console.Write( "No" + "\n" );
}
}
|
Javascript
<script>
function checkUniqueFrequency(arr, n)
{
let freq = new Map();
for (let i = 0; i < n; i++)
{
if (freq.has(arr[i]))
{
freq.set(arr[i],
freq.get(arr[i]) + 1);
}
else
{
freq.set(arr[i], 1);
}
}
let uniqueFreq = new Set();
for (let [key, value] of freq.entries())
{
if (uniqueFreq.has(value))
return false ;
else
uniqueFreq.add(value);
}
return true ;
}
let arr = [ 1, 1, 2, 5, 5 ];
let n = arr.length;
let res = checkUniqueFrequency(arr, n);
if (res)
document.write( "Yes" + "<br>" );
else
document.write( "No" + "<br>" );
</script>
|
Time Complexity: O(N), where N is the number of elements in the array.
Auxiliary Space: O(N)
Another Approach (set):
We can traverse the array and count the frequency of each element using a hash map. Then, we can insert the frequencies into a set and check if the size of the set is equal to the number of distinct frequencies. If yes, then all the frequencies are unique, otherwise not.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
bool checkUniqueFrequency( int arr[], int n)
{
unordered_map< int , int > freq;
set< int > freqSet;
for ( int i = 0; i < n; i++)
freq[arr[i]]++;
for ( auto it : freq)
freqSet.insert(it.second);
return (freqSet.size() == freq.size());
}
int main()
{
int arr[] = { 2, 2, 5, 10, 1, 2, 10, 5, 10, 2 };
int n = sizeof arr / sizeof arr[0];
bool res = checkUniqueFrequency(arr, n);
if (res)
cout << "Yes" << endl;
else
cout << "No" << endl;
return 0;
}
|
Java
import java.util.*;
public class Main {
public static boolean checkUniqueFrequency( int [] arr)
{
Map<Integer, Integer> freq = new HashMap<>();
Set<Integer> freqSet = new HashSet<>();
for ( int i : arr) {
freq.put(i, freq.getOrDefault(i, 0 ) + 1 );
}
for ( int f : freq.values()) {
freqSet.add(f);
}
return freqSet.size() == freq.size();
}
public static void main(String[] args)
{
int [] arr = { 2 , 2 , 5 , 10 , 1 , 2 , 10 , 5 , 10 , 2 };
boolean res = checkUniqueFrequency(arr);
if (res) {
System.out.println( "Yes" );
}
else {
System.out.println( "No" );
}
}
}
|
Python3
def checkUniqueFrequency(arr):
freq = {}
freqSet = set ()
for i in arr:
freq[i] = freq.get(i, 0 ) + 1
for f in freq.values():
freqSet.add(f)
return len (freqSet) = = len (freq)
arr = [ 2 , 2 , 5 , 10 , 1 , 2 , 10 , 5 , 10 , 2 ]
res = checkUniqueFrequency(arr)
if res:
print ( "Yes" )
else :
print ( "No" )
|
C#
using System;
using System.Collections.Generic;
public class GFG
{
public static bool CheckUniqueFrequency( int [] arr)
{
Dictionary< int , int > freq = new Dictionary< int , int >();
HashSet< int > freqSet = new HashSet< int >();
foreach ( int i in arr)
{
if (freq.ContainsKey(i))
{
freq[i]++;
}
else
{
freq[i] = 1;
}
}
foreach ( int f in freq.Values)
{
freqSet.Add(f);
}
return freqSet.Count == freq.Count;
}
public static void Main( string [] args)
{
int [] arr = { 2, 2, 5, 10, 1, 2, 10, 5, 10, 2 };
bool res = CheckUniqueFrequency(arr);
if (res)
{
Console.WriteLine( "Yes" );
}
else
{
Console.WriteLine( "No" );
}
}
}
|
Javascript
function checkUniqueFrequency(arr) {
let freq = {};
let freqSet = new Set();
for (let i = 0; i < arr.length; i++) {
freq[arr[i]] = (freq[arr[i]] || 0) + 1;
}
for (let f in freq) {
freqSet.add(freq[f]);
}
return freqSet.size === Object.keys(freq).length;
}
const arr = [2, 2, 5, 10, 1, 2, 10, 5, 10, 2];
const res = checkUniqueFrequency(arr);
if (res) {
console.log( "Yes" );
} else {
console.log( "No" );
}
|
Time Complexity: O(nlogn) due to the insertion operation in the set.
Auxiliary Space: O(N)
Similar Reads
Check whether the frequency of the elements in the Array is unique or not
Given an array arr[] of N integers, the task is to check whether the frequency of the elements in the array is unique or not, or in other words, there are no two distinct numbers in an array with equal frequency. If all the frequency is unique then Print "YES", else Print "NO". Examples: Input: N =
5 min read
Check if frequency of each digit in a number is equal to its value
Given a number N the task is to check whether the frequency of each digit in a number is equal to its value or notExamples: Input: N = 3331Output: YesExplanation: It is a valid number since frequency of 3 is 3, and frequency of 1 is 1Input: N = 121Output: NoExplanation: It is not a valid number sinc
4 min read
Find frequency of each element in a limited range array in less than O(n) time
Given a sorted array arr[] of positive integers, the task is to find the frequency for each element in the array. Assume all elements in the array are less than some constant M Note: Do this without traversing the complete array. i.e. expected time complexity is less than O(n) Examples: Input: arr[]
10 min read
Find the frequency of each element in a sorted array
Given a sorted array, arr[] consisting of N integers, the task is to find the frequencies of each array element. Examples: Input: arr[] = {1, 1, 1, 2, 3, 3, 5, 5, 8, 8, 8, 9, 9, 10} Output: Frequency of 1 is: 3 Frequency of 2 is: 1 Frequency of 3 is: 2 Frequency of 5 is: 2 Frequency of 8 is: 3 Frequ
10 min read
Cumulative frequency of count of each element in an unsorted array
Given an unsorted array. The task is to calculate the cumulative frequency of each element of the array using a count array. Examples: Input : arr[] = [1, 2, 2, 1, 3, 4]Output :1->2 2->4 3->5 4->6Input : arr[] = [1, 1, 1, 2, 2, 2]Output :1->3 2->6 A simple solution is to use two ne
9 min read
Check if the sum of K least and most frequent array elements are equal or not
Given an array arr[] consisting of N integers, the task is to check if the sum of K most frequent array elements and the sum of K least frequent array elements in the array arr[] are equal or not. If found to be true, then print Yes. Otherwise, print No. Examples: Input: arr[] = { 3, 2, 1, 2, 3, 3,
10 min read
Count frequencies of all elements in array in Python using collections module
Given an unsorted array of n integers which can contains n integers. Count frequency of all elements that are present in array. Examples: Input : arr[] = [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 4, 5, 5] Output : 1 -> 4 2 -> 4 3 -> 2 4 -> 1 5 -> 2 This problem can be solved in many ways, refer
2 min read
Check if Array elements of given range form a permutation
Given an array arr[] consisting of N distinct integers and an array Q[][2] consisting of M queries of the form [L, R], the task for each query is to check if array elements over the range [L, R] forms a permutation or not. Note: A permutation is a sequence of length N containing each number from 1 t
10 min read
Print all Distinct ( Unique ) Elements in given Array
Given an integer array arr[], print all distinct elements from this array. The given array may contain duplicates and the output should contain every element only once. Examples: Input: arr[] = {12, 10, 9, 45, 2, 10, 10, 45}Output: {12, 10, 9, 45, 2} Input: arr[] = {1, 2, 3, 4, 5}Output: {1, 2, 3, 4
11 min read
Check if frequency of each character is equal to its position in English Alphabet
Given string str of lowercase alphabets, the task is to check if the frequency of each distinct characters in the string equals to its position in the English Alphabet. If valid, then print "Yes", else print "No". Examples: Input: str = "abbcccdddd" Output: Yes Explanation: Since frequency of each d
8 min read