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++
// C++ program to count smaller or equal
// elements in sorted array.
#include <bits/stdc++.h>
using namespace std;
// Simple linear traversal for counting
int countOfElements(int arr[], int n, int x)
{
// here the index is used as count
// declared a variable to count
int i = 0;
for (i = 0; i < n; i++) {
// break when find
// greater element
if (arr[i] > x)
break;
}
// return the count
return i;
}
// Driver Code
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;
}
// this code is contributed by rajdeep999
Java
// Java program to count smaller or equal
// elements in sorted array.
import java.io.*;
class GFG {
// Simple linear traversal for counting
static int countOfElements(int arr[], int n, int key)
{
// here the index is used as count
// declared a variable to count
int i = 0;
for (i = 0; i < n; i++) {
// break when find
// greater element
if (arr[i] > key)
break;
}
// return the count
return i;
}
// Driver Code
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));
}
}
// this code is contributed by rajdeep999
Python3
class GFG :
# Simple linear traversal for counting
@staticmethod
def countOfElements( arr, n, key) :
# here the index is used as count
# declared a variable to count
i = 0
i = 0
while (i < n) :
# break when find
# greater element
if (arr[i] > key) :
break
i += 1
# return the count
return i
# Driver Code
@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([])
# This code is contributed by aadityaburujwale.
C#
// Include namespace system
using System;
public class GFG
{
// Simple linear traversal for counting
public static int countOfElements(int[] arr, int n, int key)
{
// here the index is used as count
// declared a variable to count
var i = 0;
for (i = 0; i < n; i++)
{
// break when find
// greater element
if (arr[i] > key)
{
break;
}
}
// return the count
return i;
}
// Driver Code
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));
}
}
// This code is contributed by dhanshriborse561
JavaScript
// Javascript program to count smaller or equal
// elements in sorted array.
// Simple linear traversal for counting
function countOfElements(arr, n, x)
{
// here the index is used as count
// declared a variable to count
let i = 0;
for (i = 0; i < n; i++) {
// break when find
// greater element
if (arr[i] > x)
break;
}
// return the count
return i;
}
// Driver Code
let arr = [ 1, 2, 4, 5, 8, 10 ];
let key = 11;
let n = arr.length;
console.log(countOfElements(arr, n, key));
// This code is contributed by Pushpesh Raj.
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++
// C++ program to count smaller or equal
// elements in sorted array.
#include <bits/stdc++.h>
using namespace std;
// A binary search function. It returns
// number of elements less than of equal
// to given key
int binarySearchCount(int arr[], int n, int key)
{
int left = 0, right = n;
int mid;
while (left < right) {
mid = (right + left) >> 1;
// Check if key is present in array
if (arr[mid] == key) {
// If duplicates are present it returns
// the position of last element
while (mid + 1 < n && arr[mid + 1] == key)
mid++;
break;
}
// If key is smaller, ignore right half
else if (arr[mid] > key)
right = mid;
// If key is greater, ignore left half
else
left = mid + 1;
}
// If key is not found
// in array then it will be
// before mid
while (mid > -1 && arr[mid] > key)
mid--;
// Return mid + 1 because of 0-based indexing
// of array
return mid + 1;
}
// Driver program to test binarySearchCount()
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
// Java program to count smaller or equal
// elements in sorted array.
class GFG {
// A binary search function. It returns
// number of elements less than of equal
// to given key
static int binarySearchCount(int arr[], int n, int key)
{
int left = 0, right = n;
int mid = 0;
while (left < right) {
mid = (right + left) >> 1;
// Check if key is present in array
if (arr[mid] == key) {
// If duplicates are present it returns
// the position of last element
while (mid + 1 < n && arr[mid + 1] == key)
mid++;
break;
}
// If key is smaller, ignore right half
else if (arr[mid] > key)
right = mid;
// If key is greater, ignore left half
else
left = mid + 1;
}
// If key is not found in array then it will be
// before mid
while (mid > -1 && arr[mid] > key)
mid--;
// Return mid + 1 because of 0-based indexing
// of array
return mid + 1;
}
// Driver code
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));
}
}
// This code is contributed by Anant Agarwal.
Python3
# Python program to
# count smaller or equal
# elements in sorted array.
# A binary search function.
# It returns
# number of elements
# less than of equal
# to given key
def binarySearchCount(arr, n, key):
left = 0
right = n
mid = 0
while (left < right):
mid = (right + left)//2
# Check if key is present in array
if (arr[mid] == key):
# If duplicates are
# present it returns
# the position of last element
while (mid + 1<n and arr[mid + 1] == key):
mid+= 1
break
# If key is smaller,
# ignore right half
elif (arr[mid] > key):
right = mid
# If key is greater,
# ignore left half
else:
left = mid + 1
# If key is not found in
# array then it will be
# before mid
while (mid > -1 and arr[mid] > key):
mid-= 1
# Return mid + 1 because
# of 0-based indexing
# of array
return mid + 1
# Driver code
arr = [1, 2, 4, 5, 8, 10]
key = 11
n = len(arr)
print(binarySearchCount(arr, n, key))
# This code is contributed
# by Anant Agarwal.
C#
// C# program to count smaller or
// equal elements in sorted array.
using System;
class GFG {
// A binary search function.
// It returns number of elements
// less than of equal to given key
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;
// Check if key is
// present in array
if (arr[mid] == key) {
// If duplicates are present
// it returns the position
// of last element
while (mid + 1 < n && arr[mid + 1] == key)
mid++;
break;
}
// If key is smaller,
// ignore right half
else if (arr[mid] > key)
right = mid;
// If key is greater,
// ignore left half
else
left = mid + 1;
}
// If key is not found in array
// then it will be before mid
while (mid > -1 && arr[mid] > key)
mid--;
// Return mid + 1 because of
// 0-based indexing of array
return mid + 1;
}
// Driver code
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));
}
}
// This code is contributed by ajit.
PHP
<?php
// PHP program to count
// smaller or equal
// elements in sorted array.
// A binary search function.
// It returns number of
// elements less than of
// equal to given key
function binarySearchCount($arr, $n, $key)
{
$left = 0;
$right = $n;
$mid;
while ($left < $right)
{
$mid = ($right + $left) / 2;
// Check if key is
// present in array
if ($arr[$mid] == $key)
{
// If duplicates are
// present it returns
// the position of
// last element
while ($mid + 1 < $n && $arr[$mid + 1] == $key)
$mid++;
break;
}
// If key is smaller,
// ignore right half
else if ($mid > -1 && $arr[$mid] > $key)
$right = $mid;
// If key is greater,
// ignore left half
else
$left = $mid + 1;
}
// If key is not found in
// array then it will be
// before mid
while ($arr[$mid] > $key)
$mid--;
// Return mid + 1 because
// of 0-based indexing
// of array
return $mid + 1;
}
// Driver Code
$arr = array (1, 2, 4,
5, 8, 10);
$key = 11;
$n = sizeof($arr) ;
echo binarySearchCount($arr, $n, $key);
// This code is contributed by ajit
?>
JavaScript
<script>
// Javascript program to
// count smaller or equal
// elements in sorted array.
// A binary search function. It returns
// number of elements less than of equal
// to given key
function binarySearchCount(arr, n, key)
{
let left = 0, right = n;
let mid;
while (left < right) {
mid = (right + left) >> 1;
// Check if key is present in array
if (arr[mid] == key) {
// If duplicates are
// present it returns
// the position of last element
while ((mid + 1) < n &&
arr[mid + 1] == key)
mid++;
break;
}
// If key is smaller, ignore right half
else if (arr[mid] > key)
right = mid;
// If key is greater, ignore left half
else
left = mid + 1;
}
// If key is not found
// in array then it will be
// before mid
while (mid > -1 && arr[mid] > key)
mid--;
// Return mid + 1 because of 0-based indexing
// of array
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++
// C++ program to count smaller or equal
// elements in sorted array
#include <bits/stdc++.h>
using namespace std;
// A binary search function to return
// the number of elements less than
// or equal to the given key
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;
// Check if middle element is
// less than or equal to key
if (arr[mid] <= key) {
// At least (mid + 1) elements are there
// whose values are less than
// or equal to key
count = mid + 1;
left = mid + 1;
}
// If key is smaller, ignore right half
else
right = mid - 1;
}
return count;
}
// Driver code
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
// Java program to count smaller or equal
import java.io.*;
class GFG
{
// A binary search function to return
// the number of elements less than
// or equal to the given key
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;
// Check if middle element is
// less than or equal to key
if (arr[mid] <= key)
{
// At least (mid + 1) elements are there
// whose values are less than
// or equal to key
count = mid + 1;
left = mid + 1;
}
// If key is smaller, ignore right half
else
right = mid - 1;
}
return count;
}
// Driver code
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));
}
}
// The code is contributed by Sachin.
Python3
# Python3 program to count smaller or equal
# elements in sorted array
# A binary search function to return
# the number of elements less than
# or equal to the given key
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left) / 2)
# Check if middle element is
# less than or equal to key
if (arr[mid] <= key):
# At least (mid + 1) elements are there
# whose values are less than
# or equal to key
count = mid + 1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# Driver code
arr = [ 1, 2, 4, 11, 11, 16 ]
key = 11
n = len(arr)
print( binarySearchCount(arr, n, key))
# This code is contributed by Arnab Kundu
C#
// C# program to count smaller or equal
using System;
class GFG
{
// A binary search function to return
// the number of elements less than
// or equal to the given key
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;
// Check if middle element is
// less than or equal to key
if (arr[mid] <= key)
{
// At least (mid + 1) elements are there
// whose values are less than
// or equal to key
count = mid + 1;
left = mid + 1;
}
// If key is smaller,
// ignore right half
else
right = mid - 1;
}
return count;
}
// Driver code
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));
}
}
// This code is contributed by PrinciRaj1992
JavaScript
<script>
// Javascript program to count smaller or equal
// elements in sorted array
// A binary search function to return
// the number of elements less than
// or equal to the given key
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);
// Check if middle element is
// less than or equal to key
if (arr[mid] <= key) {
// At least (mid + 1) elements are there
// whose values are less than
// or equal to key
count = mid + 1;
left = mid + 1;
}
// If key is smaller, ignore right half
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));
// This code is contributed by rameshtravel07.
</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++
// c++ code for the above approach
#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
// Java code for the above approach
import java.util.*;
class GFG {
// Function to count the number of elements in an array
// that are less than or equal to a given value x
public static int countOfElements(int arr[], int n, int x)
{
int i = Arrays.binarySearch(arr, x);
if (i < 0)
i = -(i + 1);
return i;
}
// Driver code
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
# Function to count the number of elements in an array that
# are less than or equal to a given value x
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#
// C# code for the above approach
using System;
class GFG {
// Function to count the number of elements in an array
// that are less than or equal to a given value x
public static int countOfElements(int[] arr, int n,
int x)
{
int i = Array.BinarySearch(arr, x);
if (i < 0)
i = -(i + 1);
return i;
}
// Driver code
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));
}
}
// akashish__
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)
Similar Reads
Count elements smaller than or equal to x in a sorted matrix
Given a n x n strictly sorted matrix and a value x. The problem is to count the elements smaller than or equal to x in the given matrix. Here strictly sorted matrix means that matrix is sorted in a way such that all elements in a row are sorted in increasing order and for row âiâ, where 1 <= i
14 min read
Count of index pairs with equal elements in an array | Set 2
Given an array arr[] of N elements. The task is to count the total number of indices (i, j) such that arr[i] = arr[j] and i != j Examples: Input: arr[]={1, 2, 1, 1}Output: 3 Explanation:In the array arr[0]=arr[2]=arr[3]Valid Pairs are (0, 2), (0, 3) and (2, 3) Input: arr[]={2, 2, 3, 2, 3}Output: 4Ex
8 min read
Count unordered pairs of equal elements for all subarrays
Given an array arr[] consisting of N integers, the task is to find the total number of unordered pairs (i, j) in the array such that arr[i] is equal to arr[j] and i < j for all subarrays of the given array. Examples: Input: arr[] = {1, 2, 1, 1}Output: 6Explanation: All subarrays of the given arra
7 min read
Count elements less than or equal to a given value in a sorted rotated array
Given a sorted array of n distinct integers rotated at some point. Given a value x. The problem is to count all the elements in the array which are less than or equal to x. Examples: Input : arr[] = {4, 5, 8, 1, 3}, x = 6 Output : 4 Input : arr[] = {6, 10, 12, 15, 2, 4, 5}, x = 14 Output : 6 Naive A
15 min read
Count number of smallest elements in given range
You are given an array arr[] of size n consisting of integers. Additionally, you are given q queries. Each query is represented by a pair [l, r], where 0 ⤠l ⤠r < n.For each query, determine the number of times the smallest element appears in the subarray from index l to index r (inclusive).Exam
15+ min read
Count of greater elements for each element in the Array
Given an array arr of integers of size N, the task is to find, for every element, the number of elements that are greater than it.Examples: Input: arr[] = {4, 6, 2, 1, 8, 7} Output: {3, 2, 4, 5, 0, 1}Input: arr[] = {2, 3, 4, 5, 6, 7, 8} Output: {6, 5, 4, 3, 2, 1, 0} Approach: Store the frequencies o
5 min read
Count of smaller elements on right side of each element in an Array using Merge sort
Given an array arr[] of N integers, the task is to count the number of smaller elements on the right side for each of the element in the array Examples: Input: arr[] = {6, 3, 7, 2} Output: 2, 1, 1, 0 Explanation: Smaller elements after 6 = 2 [3, 2] Smaller elements after 3 = 1 [2] Smaller elements a
12 min read
Cumulative frequency of count of each element in an unsorted array
Given an unsorted array. The task is to calculate the cumulative frequency of each element of the array using a count array.Examples: Input : arr[] = [1, 2, 2, 1, 3, 4]Output :1->2 2->4 3->5 4->6Input : arr[] = [1, 1, 1, 2, 2, 2]Output :1->3 2->6 A simple solution is to use two nes
9 min read
Count sub-arrays which have elements less than or equal to X
Given an array of n elements and an integer X. Count the number of sub-arrays of this array which have all elements less than or equal to X. Examples: Input : arr[] = {1, 5, 7, 8, 2, 3, 9} X = 6 Output : 6 Explanation : Sub-arrays are {1}, {5}, {2}, {3}, {1, 5}, {2, 3} Input : arr[] = {1, 10, 12, 4,
15 min read
Count elements present in first array but not in second
Given two arrays (which may or may not be sorted) of sizes M and N respectively. Their arrays are such that they might have some common elements in them. You need to count the number of elements whose occurrences are more in the first array than second. Examples: Input : arr1[] = {41, 43, 45, 50}, M
6 min read