Count of smaller or equal elements in sorted array
Last Updated :
19 Apr, 2023
Given a sorted array of size n. Find a number of elements that are less than or equal to a given element.
Examples:
Input : arr[] = {1, 2, 4, 5, 8, 10}
key = 9
Output : 5
Elements less than or equal to 9 are 1, 2,
4, 5, 8 therefore result will be 5.
Input : arr[] = {1, 2, 2, 2, 5, 7, 9}
key = 2
Output : 4
Elements less than or equal to 2 are 1, 2,
2, 2 therefore result will be 4.
Naive approach: Iterate over the complete array and count elements that are less than or equal to the key. dhanshriborse561
C++
#include <bits/stdc++.h>
using namespace std;
int countOfElements( int arr[], int n, int x)
{
int i = 0;
for (i = 0; i < n; i++) {
if (arr[i] > x)
break ;
}
return i;
}
int main()
{
int arr[] = { 1, 2, 4, 5, 8, 10 };
int key = 11;
int n = sizeof (arr) / sizeof (arr[0]);
cout << countOfElements(arr, n, key);
return 0;
}
|
Java
import java.io.*;
class GFG {
static int countOfElements( int arr[], int n, int key)
{
int i = 0 ;
for (i = 0 ; i < n; i++) {
if (arr[i] > key)
break ;
}
return i;
}
public static void main(String[] args)
{
int arr[] = { 1 , 2 , 4 , 5 , 8 , 10 };
int key = 11 ;
int n = arr.length;
System.out.print(countOfElements(arr, n, key));
}
}
|
Python3
class GFG :
@staticmethod
def countOfElements( arr, n, key) :
i = 0
i = 0
while (i < n) :
if (arr[i] > key) :
break
i + = 1
return i
@staticmethod
def main( args) :
arr = [ 1 , 2 , 4 , 5 , 8 , 10 ]
key = 11
n = len (arr)
print (GFG.countOfElements(arr, n, key), end = "")
if __name__ = = "__main__" :
GFG.main([])
|
C#
using System;
public class GFG
{
public static int countOfElements( int [] arr, int n, int key)
{
var i = 0;
for (i = 0; i < n; i++)
{
if (arr[i] > key)
{
break ;
}
}
return i;
}
public static void Main(String[] args)
{
int [] arr = {1, 2, 4, 5, 8, 10};
var key = 11;
var n = arr.Length;
Console.Write(GFG.countOfElements(arr, n, key));
}
}
|
Javascript
function countOfElements(arr, n, x)
{
let i = 0;
for (i = 0; i < n; i++) {
if (arr[i] > x)
break ;
}
return i;
}
let arr = [ 1, 2, 4, 5, 8, 10 ];
let key = 11;
let n = arr.length;
console.log(countOfElements(arr, n, key));
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Efficient approach: As the whole array is sorted we can use binary search to find results.
- Case 1: When the key is present in the array, the last position of the key is the result.
- Case 2: When the key is not present in the array, we ignore the left half if the key is greater than mid. If the key is smaller than mid, we ignore the right half. We always end up with a case where the key is present before the middle element.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
int binarySearchCount( int arr[], int n, int key)
{
int left = 0, right = n;
int mid;
while (left < right) {
mid = (right + left) >> 1;
if (arr[mid] == key) {
while (mid + 1 < n && arr[mid + 1] == key)
mid++;
break ;
}
else if (arr[mid] > key)
right = mid;
else
left = mid + 1;
}
while (mid > -1 && arr[mid] > key)
mid--;
return mid + 1;
}
int main()
{
int arr[] = { 1, 2, 4, 5, 8, 10 };
int key = 11;
int n = sizeof (arr) / sizeof (arr[0]);
cout << binarySearchCount(arr, n, key);
return 0;
}
|
Java
class GFG {
static int binarySearchCount( int arr[], int n, int key)
{
int left = 0 , right = n;
int mid = 0 ;
while (left < right) {
mid = (right + left) >> 1 ;
if (arr[mid] == key) {
while (mid + 1 < n && arr[mid + 1 ] == key)
mid++;
break ;
}
else if (arr[mid] > key)
right = mid;
else
left = mid + 1 ;
}
while (mid > - 1 && arr[mid] > key)
mid--;
return mid + 1 ;
}
public static void main(String[] args)
{
int arr[] = { 1 , 2 , 4 , 5 , 8 , 10 };
int key = 11 ;
int n = arr.length;
System.out.print(binarySearchCount(arr, n, key));
}
}
|
Python3
def binarySearchCount(arr, n, key):
left = 0
right = n
mid = 0
while (left < right):
mid = (right + left) / / 2
if (arr[mid] = = key):
while (mid + 1 <n and arr[mid + 1 ] = = key):
mid + = 1
break
elif (arr[mid] > key):
right = mid
else :
left = mid + 1
while (mid > - 1 and arr[mid] > key):
mid - = 1
return mid + 1
arr = [ 1 , 2 , 4 , 5 , 8 , 10 ]
key = 11
n = len (arr)
print (binarySearchCount(arr, n, key))
|
C#
using System;
class GFG {
static int binarySearchCount( int [] arr,
int n, int key)
{
int left = 0;
int right = n;
int mid = 0;
while (left < right) {
mid = (right + left) / 2;
if (arr[mid] == key) {
while (mid + 1 < n && arr[mid + 1] == key)
mid++;
break ;
}
else if (arr[mid] > key)
right = mid;
else
left = mid + 1;
}
while (mid > -1 && arr[mid] > key)
mid--;
return mid + 1;
}
static public void Main()
{
int [] arr = { 1, 2, 4, 5, 8, 10 };
int key = 11;
int n = arr.Length;
Console.Write(binarySearchCount(arr, n, key));
}
}
|
PHP
<?php
function binarySearchCount( $arr , $n , $key )
{
$left = 0;
$right = $n ;
$mid ;
while ( $left < $right )
{
$mid = ( $right + $left ) / 2;
if ( $arr [ $mid ] == $key )
{
while ( $mid + 1 < $n && $arr [ $mid + 1] == $key )
$mid ++;
break ;
}
else if ( $mid > -1 && $arr [ $mid ] > $key )
$right = $mid ;
else
$left = $mid + 1;
}
while ( $arr [ $mid ] > $key )
$mid --;
return $mid + 1;
}
$arr = array (1, 2, 4,
5, 8, 10);
$key = 11;
$n = sizeof( $arr ) ;
echo binarySearchCount( $arr , $n , $key );
?>
|
Javascript
<script>
function binarySearchCount(arr, n, key)
{
let left = 0, right = n;
let mid;
while (left < right) {
mid = (right + left) >> 1;
if (arr[mid] == key) {
while ((mid + 1) < n &&
arr[mid + 1] == key)
mid++;
break ;
}
else if (arr[mid] > key)
right = mid;
else
left = mid + 1;
}
while (mid > -1 && arr[mid] > key)
mid--;
return mid + 1;
}
let arr = [ 1, 2, 4, 5, 8, 10 ];
let key = 11;
let n = arr.length;
document.write(binarySearchCount(arr, n, key));
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Although this solution performs better on average, the worst-case time complexity of this solution is still O(n).
The above program can be implemented using a more simplified binary search. The idea is to check if the middle element is greater than the given element and then update right index as mid – 1 but if the middle element is less than or equal to the key update answer as mid + 1 and the left index as mid + 1.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int binarySearchCount( int arr[], int n, int key)
{
int left = 0;
int right = n - 1;
int count = 0;
while (left <= right) {
int mid = (right + left) / 2;
if (arr[mid] <= key) {
count = mid + 1;
left = mid + 1;
}
else
right = mid - 1;
}
return count;
}
int main()
{
int arr[] = { 1, 2, 4, 11, 11, 16 };
int key = 11;
int n = sizeof (arr) / sizeof (arr[0]);
cout << binarySearchCount(arr, n, key);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static int binarySearchCount( int arr[],
int n, int key)
{
int left = 0 ;
int right = n - 1 ;
int count = 0 ;
while (left <= right)
{
int mid = (right + left) / 2 ;
if (arr[mid] <= key)
{
count = mid + 1 ;
left = mid + 1 ;
}
else
right = mid - 1 ;
}
return count;
}
public static void main (String[] args)
{
int arr[] = { 1 , 2 , 4 , 11 , 11 , 16 };
int key = 11 ;
int n = arr.length;
System.out.println (binarySearchCount(arr, n, key));
}
}
|
Python3
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left < = right):
mid = int ((right + left) / 2 )
if (arr[mid] < = key):
count = mid + 1
left = mid + 1
else :
right = mid - 1
return count
arr = [ 1 , 2 , 4 , 11 , 11 , 16 ]
key = 11
n = len (arr)
print ( binarySearchCount(arr, n, key))
|
C#
using System;
class GFG
{
static int binarySearchCount( int []arr,
int n, int key)
{
int left = 0;
int right = n - 1;
int count = 0;
while (left <= right)
{
int mid = (right + left) / 2;
if (arr[mid] <= key)
{
count = mid + 1;
left = mid + 1;
}
else
right = mid - 1;
}
return count;
}
public static void Main (String[] args)
{
int []arr = { 1, 2, 4, 11, 11, 16 };
int key = 11;
int n = arr.Length;
Console.WriteLine(binarySearchCount(arr, n, key));
}
}
|
Javascript
<script>
function binarySearchCount(arr, n, key)
{
let left = 0;
let right = n - 1;
let count = 0;
while (left <= right) {
let mid = parseInt((right + left) / 2, 10);
if (arr[mid] <= key) {
count = mid + 1;
left = mid + 1;
}
else
right = mid - 1;
}
return count;
}
let arr = [ 1, 2, 4, 11, 11, 16 ];
let key = 11;
let n = arr.length;
document.write(binarySearchCount(arr, n, key));
</script>
|
Time Complexity: O(log(n))
Auxiliary Space: O(1)
Another Approach: Using standard in-built library functions such as upper_bound. The returns an iterator pointing to the first element in the range [first, last] greater than the value, or last if no such element is found. For more details on the upper_bound function refer to https://www.geeksforgeeks.org/upper_bound-in-cpp/
Below is the code for the same.
C++
#include <bits/stdc++.h>
using namespace std;
int countOfElements( int arr[], int n, int x)
{
int i = upper_bound(arr, arr + n, x) - arr;
return i;
}
int main()
{
int arr[] = { 1, 2, 4, 5, 8, 10 };
int key = 9;
int n = sizeof (arr) / sizeof (arr[0]);
cout << countOfElements(arr, n, key);
return 0;
}
|
Java
import java.util.*;
class GFG {
public static int countOfElements( int arr[], int n, int x)
{
int i = Arrays.binarySearch(arr, x);
if (i < 0 )
i = -(i + 1 );
return i;
}
public static void main(String args[])
{
int arr[] = { 1 , 2 , 4 , 5 , 8 , 10 };
int key = 9 ;
int n = arr.length;
System.out.println(countOfElements(arr, n, key));
}
}
|
Python3
from bisect import bisect_right
def countOfElements(arr, n, x):
i = bisect_right(arr, x)
return i
arr = [ 1 , 2 , 4 , 5 , 8 , 10 ]
key = 9
n = len (arr)
print (countOfElements(arr,n,key))
|
C#
using System;
class GFG {
public static int countOfElements( int [] arr, int n,
int x)
{
int i = Array.BinarySearch(arr, x);
if (i < 0)
i = -(i + 1);
return i;
}
public static void Main( string [] args)
{
int [] arr = { 1, 2, 4, 5, 8, 10 };
int key = 9;
int n = arr.Length;
Console.WriteLine(countOfElements(arr, n, key));
}
}
|
Javascript
function countOfElements(arr, n, x) {
let i = arr.findIndex(a => a > x);
return i === -1 ? n : i;
}
let arr = [1, 2, 4, 5, 8, 10];
let key = 9;
let n = arr.length;
console.log(countOfElements(arr, n, key));
|
Time Complexity: O(log(n))
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...