Count number of occurrences (or frequency) of each element in a sorted array

Table of Contents

If you want to practice data structure and algorithm programs, you can go through Java coding interview questions.

In this post, we will see how to count number of occurrences (or frequency) of each element in a sorted array


Given a Sorted Array of integers containing duplicates. Find the frequency of every unique element present in the array.
Frequency is defined as the number of occurrence of any element in the array.

For example :

int[] arr = {2, 2, 2, 3, 3, 4, 5, 5, 6, 6};

Frequency of 2 is : 3
Frequency of 3 is : 2
Frequency of 4 is : 1
Frequency of 5 is : 2
Frequency of 6 is : 2


Lets first Discuss the basic divide and conquer strategy to solve this problem.
we divide the array into two halves every time our function is called splitting our problem into half every time giving rise to a worst time complexity of O(log(n)).

Our array is not actually divided into halves, but we keep two pointers start and end representing some portion of array to work with and this is how our array is virtually split.

We know that our array is already sorted. So we can conclude that,

  • if the elements at start pointer and end pointer are equal to the element whose frequency is to be calculated, this means that whole virtual array contains that element only and hence we directly add (end-start+1) to our frequency count.
  • If this is not the case, we recur for the two halves of the array and in post order we will add the calls of these two result to make our final frequency count result.

Now, This whole algorithm was for finding the frequency of one element in the array.
For finding the frequency of every element this function needs to be called every time.
Hence the overall worst time complexity for solving this problem with this algorithm will be


There is an iterative and even efficient approach also which solves the problem in single parse in linear time i.e. O(n).

What we can do is, we keep a frequency array and loop through the array, and every time we find any element we go to the frequency array and add 1 to the previous frequency of that element in the frequency array.
After the loop ends, we are left with an array where at every index their frequency in the original array is present.
And also the biggest plus point along with its efficiency is, We don’t necessarily need the array to be sorted.

For eg :
Consider an Array and its frequency array,
int[] arr = {5,4,3,2,4,3,2,5,5};
int[] freqArr = {0,0,0,0,0,0};
the frequency array after the loop ends will look like,
int[] freqArr = {0,0,2,2,1,3};

In this frequency array, at every i th index, the frequency of  i in actual array is sitting.

By this time, we have already known the shortcomings of this approach,
Yes, this approach will not be effective when the input array contains negative numbers or numbers greater than 10^9.
Because we do not have any negative indices and an array of size 10^9 is not possible.
so for handling that, we need to use Hashmap where we store the element-frequency pair as the key-value pair in hashmap.

When you run above program, you will get below output

4 3 2 2 3 4 4 5
arr[]: { 4 3 2 2 3 4 4 5 }
Frequency of 2 is : 2
Frequency of 3 is : 2
Frequency of 4 is : 3
Frequency of 5 is : 1

Comment in case of any doubt or edit. Happy Learning 🙂

Was this post helpful?


You may also like:

Related Posts

  • Maximum number of vowels in a Substring of given length
    18 June

    Maximum Number of Vowels in a Substring of Given Length

    Table of ContentsApproach – 1 Generate All Substrings Using substring() MethodApproach – 2 Using Sliding Window Method (Linear Time Solution) In this article, we will look at an interesting problem related to the Strings and [Sliding-Window Algorithm]( “Sliding-Window Algorithm”). The problem is : "Given a String we have to Find the Maximum Number of Vowel […]

  • Find first and last position of element in sorted array
    04 June

    Search for a range Leetcode – Find first and last position of element in sorted array

    Table of ContentsApproach 1 (Using Linear Search)Approach 2 (Using Modified Binary Search-Optimal) In this article, we will look into an interesting problem asked in Coding Interviews related to Searching Algorithms. The problem is: Given a Sorted Array, we need to find the first and last position of an element in Sorted array. This problem is […]

  • 30 April

    Convert Postfix to Infix in Java

    Learn about how to convert Postfix to Infix in java.

  • Prefix to postfix in java
    30 April

    Convert Prefix to Postfix in Java

    Learn about how to convert Prefix to Postfix in java.

  • Data structures in java
    16 April

    Data Structures in java

    Table of ContentsArray Declare and initialize array in javaAdvantages of arrayDisadvantages of array ExampleArray practice programsStackStack implementation using ArrayStack implementation using LinkedListImplementationPractice ProgramsQueueQueue implementation using arrayQueue implementation using LinkedListImplementationLinkedListImplementationLinkedList Practice ProgramsBinary treeImplementationBinary tree practice programsBinary Search treeImplementationBinary search tree Practice programsTrieImplementationHeapImplementationGraphImplementation Inbuild data structures in javaStringHashMapLinkedHashMapArrayListLinkedListHashSet In this post, we will see about various data […]

  • 29 November

    Top 100+ Java coding interview questions

    Table of ContentsStringQuestion 1 : How to reverse a String in java? Can you write a program without using any java inbuilt methods?Question 2 : Write a java program to check if two Strings are anagram in java?Question 3 : Write a program to check if String has all unique characters in java?Question 4 : […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.