If you want to practice data structure and algorithm programs, you can go through 100+ data structure and algorithm programs.

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

## Problem

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 :

**Input**:

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

**Output**:

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

## Solution

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

`O(n*log(n))`

.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
package org.arpit.java2blog; import java.util.HashSet; import java.util.Scanner; public class FreqOfEachElems { public static void main(String[] args) { Scanner scn = new Scanner(System.in); int[] arr = new int[scn.nextInt()]; for (int i = 0; i < arr.length; i++) { arr[i] = scn.nextInt(); } HashSet<Integer> processed = new HashSet(); for (int val : arr) { if (!processed.contains(val)) { System.out.println("Frequency of " + val + " is : " + solveRecursive(0, arr.length - 1, arr, val)); processed.add(val); } } } public static int solveRecursive(int start, int end, int[] arr, int element) { /* if start is greater than n, we need to return because this represent a subarray of negative size.*/ if (start > end) { return 0; } /* this means that the size of the virtual subarray is one, * and it has only single element. */ if (start == end) { /* now if this single element is equal to the element * whose frequency we are finding out, * then it will contribute one for its total frequency * in the whole array. */ if (arr[start] == element && arr[end] == element) { return 1; } else { return 0; } } /* if the virtual subarray is of size greater than one, * and the elements at start and at the end are equal, * this means that whole array consists of * that element only, as the array * we are working on is already sorted.*/ if (arr[start] == element && arr[end] == element) { return (end - start + 1); } int mid = (start + end) / 2; /* call for left side virtual subarray */ int leftResult = solveRecursive(start, mid, arr, element); /* call for right side virtual subarray.*/ int rightResult = solveRecursive(mid + 1, end, arr, element); /* our result will be calculated in postorder, * which will be left side result * plus the right side sum.*/ return leftResult + rightResult; } } |

**EFFICIENT APPROACH:**

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.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
package org.arpit.java2blog; import java.util.HashMap; import java.util.HashSet; import java.util.Scanner; public class FreqOfEachElems { public static void main(String[] args) { Scanner scn = new Scanner(System.in); int[] arr = new int[scn.nextInt()]; for (int i = 0; i < arr.length; i++) { arr[i] = scn.nextInt(); } System.out.print("arr[]: {"); for (int i = 0; i < arr.length; i++) { System.out.print(" "+arr[i]); } System.out.println(" }"); HashMap<Integer, Integer> freqMap = solveIterative(arr); for(int val : freqMap.keySet()) { System.out.println("Frequency of " + val + " is : " + freqMap.get(val)); } } public static HashMap<Integer, Integer> solveIterative(int[] arr) { HashMap<Integer, Integer> freqMap = new HashMap<>(); /* iterate through the array for contributing +1 * as a frequency of that element, every time it is encountered.*/ for(int val : arr) { if(!freqMap.containsKey(val)) { /* if hashmap doesnt contains that element, * this means this is the first time the element is encountered, * therefor freq of this element will be one for now.*/ freqMap.put(val, 1); } else { /* if hashmap contains this element, * so now its updated frequency will be its past frequency + 1. */ freqMap.put(val, freqMap.get(val)+1); } } return freqMap; } } |

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 ðŸ™‚