Count Frequency of a Number in a Sorted Array

Count Frequency of a Number in a Sorted Array.

Given a sorted array and a number k. We have to write a code to count how many times a number k appears in a sorted array.

For example –

Input: { 1, 4, 7, 8, 8, 11, 11, 11, 11, 12, 13 }, k = 11

Output: 4

In this input array, The number 11 appears Four time.

Count how many times a number k appears in a sorted array

In this tutorial, I am going discuss multiple approaches and their time complexities to solve this problem.

Also, i have shared the video tutorial at the end of this post.

Programming video tutorials

Count Number of Occurrences in Array using Linear Search – Java Code

The simplest approach is to traverse an array from left to right. Increment the value of count when current array element is equal to the number k.

The time complexity of this approach is O(n).

Let’s write a java code to implement this approach.

Count Frequency of a Number in a Sorted Array using Binary Search – Java Code

The array is sorted. We can use Binary search to find the first and last position of a number k in this sorted array.

Once the first and last position of a number is found in an array. We can easily calculate the number of occurrences. The number of occurrences is (lastPosition – firstPosition) + 1.

This approach is similar to find first and last position of a number in a sorted array

The time complexity of this approach is O(logn).

Tagged , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.