Open in App
Not now

# Javascript program for counting frequencies of array elements

• Last Updated : 21 Mar, 2023

In this article, we are given an array that may contain duplicate values. We will print all elements and their frequencies if the duplicates exist. We can do this by using two methods:

• Running two loops
• Using Hashing
• Using the Binary search function

Examples:

```Input :  arr[] = {10, 20, 20, 10, 10, 20, 5, 20}
Output : 10 3
20 4
5  1

Input : arr[] = {10, 20, 20}
Output : 10 1
20 2 ```

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

Example 1: Below is the implementation of the above approach:

## Javascript

 ``

Output:

```10 3
20 4
5 1```

Example 2: An efficient solution is to use hashing:

## Javascript

 ``

Output:

```5 1
10 3
20 4```

Example 3: In the above efficient solution, how to print elements in the same order as they appear in input:

## Javascript

 ``

Output:

```10 3
20 4
5 1```

Another Efficient Solution (Space optimization): we can find the frequency of array elements using the Binary search function. First, we will sort the array for binary search. Our frequency of element will be â€˜(last occ â€“ first occ)+1â€™ of an element in an array.

Example:

## Javascript

 `//Function to find frequency of elements in the array` `function` `countFreq(arr, n) {` `    ``arr.sort((a, b) => a - b); ``//sort array for binary search` `    ``let i = 0;` `    ``while` `(i < n) {` `        ``//index of first and last occ of arr[i]` `        ``const first_index = arr.indexOf(arr[i]);` `        ``const last_index = arr.lastIndexOf(arr[i]);` `        ``i = last_index;`   `        ``const fre = last_index - first_index + 1; ``//finding frequency` `        ``console.log(arr[i] + ``" "` `+ fre); ``//printing frequency` `        ``i++;` `    ``}` `}`   `// Driver code` `const arr = [10, 20, 20, 10, 10, 20, 5, 20];` `countFreq(arr, arr.length);`

Output

```5 1
10 3
20 4```

Time Complexity: O(n*log2n), where O(log2n) time for the binary search function.
Auxiliary Space: O(1)

My Personal Notes arrow_drop_up
Related Articles