VOOZH about

URL: https://www.geeksforgeeks.org/dsa/counting-frequencies-of-array-elements/

⇱ Counting frequencies of array elements - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Counting frequencies of array elements

Last Updated : 26 Jul, 2025

Given an array arr[] of non-negative integers which may contain duplicate elements. Return the frequency of each distinct element present in the array.

Examples: 

Input: arr[] = [10, 20, 10, 5, 20]
Output: [[5, 1], [10, 2], [20, 2]]
Explanation: Here 5 occurs once, 10 occurs 2 times and 20 occurs 2 times.

Input: arr[] = [10, 20, 20]
Output: [[10, 1], [20, 2]]
Explanation: Here 10 occurs 1 time, 20 occurs 2 times.

[Naive Approach] Brute Force - O(n2) Time O(n) Space

A simple solution is to run two loops. For every item count number of times, it occurs. To avoid duplicate printing, keep track of processed items.


Output
5 1
10 2
20 2

[Better Approach] Using binary search

We can find frequency of array elements using Binary search function . First we will sort the array for binary search . Our frequency of element will be '(last occ - first occ) + 1' of a element in a array.


Output
5 1
10 2
20 2

Time Complexity: O(n × log2n) , where O(log2n) time for binary search function.
Auxiliary Space: O(1), as using constant extra space

[Expected Solution] Using hashing - O(n) Time and O(n) Space

An efficient solution is using a hash map (e.g. unordered_map in C++, HashMap in Java, dict in Python, or Dictionary in C#), we can store elements as keys and their frequencies as values.


Output
5 1
10 2
20 2
Comment
Article Tags:
Article Tags: