Check if frequency of each element in given array is unique or not
Last Updated :
15 Jul, 2025
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++
// C++ code for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to check whether the
// frequency of elements in array
// is unique or not.
bool checkUniqueFrequency(int arr[], int n)
{
vector<int> frequency(n + 1);
// For counting the frequency of each element
for (int i = 1; i <= n; i++) {
for (int j = 0; j < n; j++) {
if (arr[j] == i) {
frequency[i - 1]++;
}
}
}
// Checking if frequency array contains any duplicate
// or not
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]) {
// If any duplicate frequency then return
// false
return false;
}
}
}
// If no duplicate frequency found, then return true
return true;
}
// Driver Code
int main()
{
// Given array arr[]
int arr[] = { 2, 2, 5, 10, 1, 2, 10, 5, 10, 2 };
int n = sizeof arr / sizeof arr[0];
// Function Call
bool res = checkUniqueFrequency(arr, n);
// Print the result
if (res)
cout << "Yes" << endl;
else
cout << "No" << endl;
return 0;
}
Java
/*package whatever //do not write package name here */
import java.io.*;
class GFG {
// Function to check whether the
// frequency of elements in array
// is unique or not.
static boolean checkUniqueFrequency(int arr[], int n)
{
int[] frequency = new int[n + 1];
// For counting the frequency of each element
for (int i = 1; i <= n; i++) {
for (int j = 0; j < n; j++) {
if (arr[j] == i) {
frequency[i - 1]++;
}
}
}
// Checking if frequency array contains any duplicate
// or not
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]) {
// If any duplicate frequency then return
// false
return false;
}
}
}
// If no duplicate frequency found, then return true
return true;
}
public static void main (String[] args) {
// Given array arr[]
int arr[] = { 2, 2, 5, 10, 1, 2, 10, 5, 10, 2 };
int n = arr.length;
// Function Call
boolean res = checkUniqueFrequency(arr, n);
// Print the result
if (res)
System.out.println("Yes");
else
System.out.println("No");
}
}
// This code is contributed by aadityaburujwale.
Python3
# Python code for the above approach
# Function to check whether the
# frequency of elements in array
# is unique or not.
def checkUniqueFrequency(arr, n):
frequency=[0]*(n + 1);
# For counting the frequency of each element
for i in range(1,n+1):
for j in range(0,n):
if (arr[j] == i):
frequency[i - 1]+=1;
# Checking if frequency array contains any duplicate
# or not
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]):
# If any duplicate frequency then return
# false
return False;
# If no duplicate frequency found, then return true
return True;
# Driver Code
# Given array arr[]
arr = [ 2, 2, 5, 10, 1, 2, 10, 5, 10, 2 ];
n = len(arr);
# Function Call
res = checkUniqueFrequency(arr, n);
# Print the result
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 counting the frequency of each element
for (int i = 1; i <= n; i++) {
for (int j = 0; j < n; j++) {
if (arr[j] == i) {
frequency[i - 1]++;
}
}
}
// Checking if frequency array contains any
// duplicate or not
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]) {
// If any duplicate frequency then
// return false
return false;
}
}
}
// If no duplicate frequency found, then return true
return true;
}
static void Main(string[] args)
{
// Given array arr[]
int[] arr = { 2, 2, 5, 10, 1, 2, 10, 5, 10, 2 };
int n = arr.Length;
// Function Call
bool res = CheckUniqueFrequency(arr, n);
// Print the result
if (res)
Console.WriteLine("Yes");
else
Console.WriteLine("No");
}
}
JavaScript
<script>
// Function to check whether the
// frequency of elements in array
// is unique or not.
function checkUniqueFrequency(arr, n)
{
var frequency = Array(n + 1).fill(0);
// For counting the frequency of each element
for (var i = 1; i <= n; i++)
{
for (var j = 0; j < n; j++)
{
if (arr[j] == i)
{
frequency[i - 1]++;
}
}
}
// Checking if frequency array contains any duplicate
// or not
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])
{
// If any duplicate frequency then return
// false
return false;
}
}
}
// If no duplicate frequency found, then return true
return true;
}
// Given array arr[]
let arr = [ 2, 2, 5, 10, 1, 2, 10, 5, 10, 2 ];
let n = arr.length;
// Function call
let res = checkUniqueFrequency(arr, n);
// Print the result
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++
// C++ code for the above approach
#include <bits/stdc++.h>
using namespace std;
// Function to check whether the
// frequency of elements in array
// is unique or not.
bool checkUniqueFrequency(int arr[],
int n)
{
// Freq map will store the frequency
// of each element of the array
unordered_map<int, int> freq;
// Store the frequency of each
// element from the array
for (int i = 0; i < n; i++) {
freq[arr[i]]++;
}
unordered_set<int> uniqueFreq;
// Check whether frequency of any
// two or more elements are same
// or not. If yes, return false
for (auto& i : freq) {
if (uniqueFreq.count(i.second))
return false;
else
uniqueFreq.insert(i.second);
}
// Return true if each
// frequency is unique
return true;
}
// Driver Code
int main()
{
// Given array arr[]
int arr[] = { 1, 1, 2, 5, 5 };
int n = sizeof arr / sizeof arr[0];
// Function Call
bool res = checkUniqueFrequency(arr, n);
// Print the result
if (res)
cout << "Yes" << endl;
else
cout << "No" << endl;
return 0;
}
Java
// Java code for the above approach
import java.util.*;
class GFG{
// Function to check whether the
// frequency of elements in array
// is unique or not.
static boolean checkUniqueFrequency(int arr[],
int n)
{
// Freq map will store the frequency
// of each element of the array
HashMap<Integer,
Integer> freq = new HashMap<Integer,
Integer>();
// Store the frequency of each
// element from the array
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>();
// Check whether frequency of any
// two or more elements are same
// or not. If yes, return false
for(Map.Entry<Integer,
Integer> i : freq.entrySet())
{
if (uniqueFreq.contains(i.getValue()))
return false;
else
uniqueFreq.add(i.getValue());
}
// Return true if each
// frequency is unique
return true;
}
// Driver Code
public static void main(String[] args)
{
// Given array arr[]
int arr[] = { 1, 1, 2, 5, 5 };
int n = arr.length;
// Function call
boolean res = checkUniqueFrequency(arr, n);
// Print the result
if (res)
System.out.print("Yes" + "\n");
else
System.out.print("No" + "\n");
}
}
// This code is contributed by PrinciRaj1992
Python3
# Python3 code for
# the above approach
from collections import defaultdict
# Function to check whether the
# frequency of elements in array
# is unique or not.
def checkUniqueFrequency(arr, n):
# Freq map will store the frequency
# of each element of the array
freq = defaultdict (int)
# Store the frequency of each
# element from the array
for i in range (n):
freq[arr[i]] += 1
uniqueFreq = set([])
# Check whether frequency of any
# two or more elements are same
# or not. If yes, return false
for i in freq:
if (freq[i] in uniqueFreq):
return False
else:
uniqueFreq.add(freq[i])
# Return true if each
# frequency is unique
return True
# Driver Code
if __name__ == "__main__":
# Given array arr[]
arr = [1, 1, 2, 5, 5]
n = len(arr)
# Function Call
res = checkUniqueFrequency(arr, n)
# Print the result
if (res):
print ("Yes")
else:
print ("No")
# This code is contributed by Chitranayal
C#
// C# code for the above approach
using System;
using System.Collections.Generic;
class GFG{
// Function to check whether the
// frequency of elements in array
// is unique or not.
static bool checkUniqueFrequency(int []arr,
int n)
{
// Freq map will store the frequency
// of each element of the array
Dictionary<int,
int> freq = new Dictionary<int,
int>();
// Store the frequency of each
// element from the array
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>();
// Check whether frequency of any
// two or more elements are same
// or not. If yes, return false
foreach(KeyValuePair<int,
int> i in freq)
{
if (uniqueFreq.Contains(i.Value))
return false;
else
uniqueFreq.Add(i.Value);
}
// Return true if each
// frequency is unique
return true;
}
// Driver Code
public static void Main(String[] args)
{
// Given array []arr
int []arr = { 1, 1, 2, 5, 5 };
int n = arr.Length;
// Function call
bool res = checkUniqueFrequency(arr, n);
// Print the result
if (res)
Console.Write("Yes" + "\n");
else
Console.Write("No" + "\n");
}
}
// This code is contributed by sapnasingh4991
JavaScript
<script>
// Javascript code for the above approach
// Function to check whether the
// frequency of elements in array
// is unique or not.
function checkUniqueFrequency(arr, n)
{
// Freq map will store the frequency
// of each element of the array
let freq = new Map();
// Store the frequency of each
// element from the array
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();
// Check whether frequency of any
// two or more elements are same
// or not. If yes, return false
for(let [key, value] of freq.entries())
{
if (uniqueFreq.has(value))
return false;
else
uniqueFreq.add(value);
}
// Return true if each
// frequency is unique
return true;
}
// Driver Code
// Given array arr[]
let arr = [ 1, 1, 2, 5, 5 ];
let n = arr.length;
// Function call
let res = checkUniqueFrequency(arr, n);
// Print the result
if (res)
document.write("Yes" + "<br>");
else
document.write("No" + "<br>");
// This code is contributed by avanitrachhadiya2155
</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 {
// Function to check the unique frequency of the array
public static boolean checkUniqueFrequency(int[] arr)
{
// Create an empty HashMap to store element
// frequencies
Map<Integer, Integer> freq = new HashMap<>();
// Create an empty HashSet to store unique
// frequencies
Set<Integer> freqSet = new HashSet<>();
// Loop through each element in the array
for (int i : arr) {
// Increment element frequency in HashMap
freq.put(i, freq.getOrDefault(i, 0) + 1);
}
// Loop through each frequency in HashMap
for (int f : freq.values()) {
// Add frequency to HashSet
freqSet.add(f);
}
// Return true if number of unique frequencies
// equals number of element frequencies
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
# Python program for the above approach
# Function to check the unique frequency
# of the array
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)
# Driver Code
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
{
// Function to check the unique frequency of the array
public static bool CheckUniqueFrequency(int[] arr)
{
// Create an empty Dictionary to store element frequencies
Dictionary<int, int> freq = new Dictionary<int, int>();
// Create an empty HashSet to store unique frequencies
HashSet<int> freqSet = new HashSet<int>();
// Loop through each element in the array
foreach (int i in arr)
{
// Increment element frequency in Dictionary
if (freq.ContainsKey(i))
{
freq[i]++;
}
else
{
freq[i] = 1;
}
}
// Loop through each frequency in Dictionary
foreach (int f in freq.Values)
{
// Add frequency to HashSet
freqSet.Add(f);
}
// Return true if number of unique frequencies
// equals number of element frequencies
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");
}
}
}
// This code is contributed by shivamgupta310570
JavaScript
// Function to check the unique frequency of the array
function checkUniqueFrequency(arr) {
let freq = {}; // Create an empty object to store frequencies
let freqSet = new Set(); // Create an empty Set to store unique frequencies
for (let i = 0; i < arr.length; i++) {
freq[arr[i]] = (freq[arr[i]] || 0) + 1; // Count the frequencies
}
for (let f in freq) {
freqSet.add(freq[f]); // Add frequencies to the set
}
// Check if set size is equal to number of unique elements
return freqSet.size === Object.keys(freq).length;
}
// Driver Code
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
Basics & Prerequisites
Data Structures
Getting Started with Array Data StructureArray is a collection of items of the same variable type that are stored at contiguous memory locations. It is one of the most popular and simple data structures used in programming. Basic terminologies of ArrayArray Index: In an array, elements are identified by their indexes. Array index starts fr
14 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem