VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-smaller-equal-elements-sorted-array/

⇱ Count less or equal to and greateror equal to in a Sorted Array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count less or equal to and greateror equal to in a Sorted Array

Last Updated : 26 Apr, 2026

Given a sorted array of size n, find the number of elements that are less than or equal to a given element and number of elements that are greater than equal to.

Examples :

Input : arr[] = {1, 2, 8, 10, 11, 12, 19} key = 0
Output : 0, 7 
Explanation : There are no elements less or equal to 0 and 7 elements greater to 0. 

Input : arr[] = {1, 5, 8, 12, 12, 12, 19} key = 12
Output : 6, 4 
Explanation : There are 6 elements less or equal to 12 and 4 elements greater or equal to 12. 

[Naive approach] : Linear Search - O(n) Time and O(1) Space

Iterate over the complete array, count elements that are less than or equal to the target, and derive the count of elements greater than the target from the remaining elements.


Output
0 7

[Efficient approach]: Binary Search - O(log n) Time and O(1) Space

As the whole array is sorted we can use binary search to find results. 

  • Do a Binary Search to find first index where element >= target. In this search, if arr[mid] >= target, we set answer and move to left side to find if there are more elements on the left side. We call this function lowerBound(). For example, if the input array is [1, 3, 4, 4, 4, 6, 7] and target is 4, then this function returns 2.
  • Do a Binary Search to find first index where element > target. In this search, if arr[mid] > target, we set answer and move to left side to find if there are more elements on the left side. We call this function upperBound(). For example, if the input array is [1, 3, 4, 4, 4, 6, 7] and target is 4, then this function returns 5.
  • The count of smaller or equal elements is equal to the value returned by upperBound(). The count of greater or equal elements is equal to size of array minus the value returned by lowerBound()

Output
0 7

Using Library

Another Approach: Using standard in-built library functions such as lower_bound and upper_bound in C++. or bisect_left and bisect_right() in Python.


Output
0 7

;;

Comment
Article Tags: