VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-number-of-occurrences-or-frequency-in-a-sorted-array/

⇱ Count number of occurrences (or frequency) in a sorted array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

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

Last Updated : 3 Oct, 2025

Given a sorted array arr[] and an integer target, find the number of occurrences of target in given array.

Examples:

Input: arr[] = [1, 1, 2, 2, 2, 2, 3], target = 2
Output: 4
Explanation: 2 occurs 4 times in the given array.

Input: arr[] = [1, 1, 2, 2, 2, 2, 3], target = 4
Output: 0
Explanation: 4 is not present in the given array.

[Naive Approach] Using Linear Search - O(n) Time and O(1) Space

The idea is to traverse the array and for each element, check if it is equal to the target. If you find any element equal to target increment the value of counter variable.


Output
4

[Expected Approach] Using Binary Search - O(log n) Time and O(1) Space

Since the array is already sorted, we can use binary search to find the occurrences of a given target. First, we find the index of the first occurrence (Lower Bound) of target and then the index of the first element greater than the target (Upper Bound). The difference between these two indices will give the total number of occurrences of the target.


Output
4
Comment