Count of larger elements on right side of each element in an array
Last Updated :
15 Jul, 2025
Given an array arr[] consisting of N integers, the task is to count the number of greater elements on the right side of each array element.
Examples:
Input: arr[] = {3, 7, 1, 5, 9, 2}
Output: {3, 1, 3, 1, 0, 0}
Explanation: For arr[0], the elements greater than it on the right are {7, 5, 9}. For arr[1], the only element greater than it on the right is {9}. For arr[2], the elements greater than it on the right are {5, 9, 2}. For arr[3], the only element greater than it on the right is {9}. For arr[4] and arr[5], no greater elements exist on the right.
Input: arr[] = {5, 4, 3, 2}
Output: {0, 0, 0, 0}
Naive Approach: The simplest approach is to iterate all array elements using two loops and for each array element, count the number of elements greater than it on its right side and then print it.
Time Complexity: O(N2)
Auxiliary Space: O(1)
Efficient Approach: The problem can be solved using the concept of Merge Sort in descending order. Follow the steps given below to solve the problem:
- Initialize an array count[] where count[i] store the respective count of greater elements on the right for every arr[i]
- Take the indexes i and j, and compare the elements in an array.
- If higher index element is greater than the lower index element then, all the higher index element will be greater than all the elements after that lower index.
- Since the left part is already sorted, add the count of elements after the lower index element to the count[] array for the lower index.
- Repeat the above steps until the entire array is sorted.
- Finally print the values of count[] array.
Below is the implementation of the above approach:
Java
// Java program for the above approach
import java.util.*;
public class GFG {
// Stores the index & value pairs
static class Item {
int val;
int index;
public Item(int val, int index)
{
this.val = val;
this.index = index;
}
}
// Function to count the number of
// greater elements on the right
// of every array element
public static ArrayList<Integer>
countLarge(int[] a)
{
// Length of the array
int len = a.length;
// Stores the index-value pairs
Item[] items = new Item[len];
for (int i = 0; i < len; i++) {
items[i] = new Item(a[i], i);
}
// Stores the count of greater
// elements on right
int[] count = new int[len];
// Perform MergeSort operation
mergeSort(items, 0, len - 1,
count);
ArrayList<Integer> res = new ArrayList<>();
for (int i : count) {
res.add(i);
}
return res;
}
// Function to sort the array
// using Merge Sort
public static void mergeSort(
Item[] items, int low ,int high,
int[] count)
{
// Base Case
if (low >= high) {
return;
}
// Find Mid
int mid = low + (high - low) / 2;
mergeSort(items, low, mid,
count);
mergeSort(items, mid + 1,
high, count);
// Merging step
merge(items, low, mid,
mid + 1, high, count);
}
// Utility function to merge sorted
// subarrays and find the count of
// greater elements on the right
public static void merge(
Item[] items, int low, int lowEnd,
int high, int highEnd, int[] count)
{
int m = highEnd - low + 1; // mid
Item[] sorted = new Item[m];
int rightCounter = 0;
int lowInd = low, highInd = high;
int index = 0;
// Loop to store the count of
// larger elements on right side
// when both array have elements
while (lowInd <= lowEnd
&& highInd <= highEnd) {
if (items[lowInd].val
< items[highInd].val) {
rightCounter++;
sorted[index++]
= items[highInd++];
}
else {
count[items[lowInd].index] += rightCounter;
sorted[index++] = items[lowInd++];
}
}
// Loop to store the count of
// larger elements in right side
// when only left array have
// some element
while (lowInd <= lowEnd) {
count[items[lowInd].index] += rightCounter;
sorted[index++] = items[lowInd++];
}
// Loop to store the count of
// larger elements in right side
// when only right array have
// some element
while (highInd <= highEnd) {
sorted[index++] = items[highInd++];
}
System.arraycopy(sorted, 0, items,
low, m);
}
// Utility function that prints
// the count of greater elements
// on the right
public static void
printArray(ArrayList<Integer> countList)
{
for (Integer i : countList)
System.out.print(i + " ");
System.out.println();
}
// Driver Code
public static void main(String[] args)
{
// Given array
int arr[] = { 3, 7, 1, 5, 9, 2 };
int n = arr.length;
// Function Call
ArrayList<Integer> countList
= countLarge(arr);
printArray(countList);
}
}
Python3
from typing import List
class Item:
def __init__(self, val: int, index: int):
self.val = val
self.index = index
def count_large(a: List[int]) -> List[int]:
# Length of the array
length = len(a)
# Stores the index-value pairs
items = [Item(a[i], i) for i in range(length)]
# Stores the count of greater elements on right
count = [0] * length
# Perform MergeSort operation
merge_sort(items, 0, length - 1, count)
res = count.copy()
return res
def merge_sort(items: List[Item], low: int, high: int, count: List[int]) -> None:
# Base Case
if low >= high:
return
# Find Mid
mid = low + (high - low) // 2
merge_sort(items, low, mid, count)
merge_sort(items, mid + 1, high, count)
# Merging step
merge(items, low, mid, mid + 1, high, count)
def merge(items: List[Item], low: int, low_end: int, high: int, high_end: int, count: List[int]) -> None:
m = high_end - low + 1 # mid
sorted_items = [None] * m
right_counter = 0
low_ind = low
high_ind = high
index = 0
# Loop to store the count of larger elements on right side
# when both array have elements
while low_ind <= low_end and high_ind <= high_end:
if items[low_ind].val < items[high_ind].val:
right_counter += 1
sorted_items[index] = items[high_ind]
index += 1
high_ind += 1
else:
count[items[low_ind].index] += right_counter
sorted_items[index] = items[low_ind]
index += 1
low_ind += 1
# Loop to store the count of larger elements in right side
# when only left array have elements
while low_ind <= low_end:
count[items[low_ind].index] += right_counter
sorted_items[index] = items[low_ind]
index += 1
low_ind += 1
# Loop to store the count of larger elements in right side
# when only right array have elements
while high_ind <= high_end:
sorted_items[index] = items[high_ind]
index += 1
high_ind += 1
items[low:low + m] = sorted_items
def print_array(count_list: List[int]) -> None:
print(' '.join(str(i) for i in count_list))
# Driver Code
if __name__ == '__main__':
# Given array
arr = [3, 7, 1, 5, 9, 2]
# Function Call
count_list = count_large(arr)
print_array(count_list)
# This code is contributed by Aditya Sharma
C#
using System;
using System.Collections.Generic;
public class GFG {
// Stores the index & value pairs
public class Item {
public int val;
public int index;
public Item(int val, int index)
{
this.val = val;
this.index = index;
}
}
// Function to count the number of
// greater elements on the right
// of every array element
public static List<int> CountLarge(int[] a)
{
// Length of the array
int len = a.Length;
// Stores the index-value pairs
Item[] items = new Item[len];
for (int i = 0; i < len; i++) {
items[i] = new Item(a[i], i);
}
// Stores the count of greater
// elements on right
int[] count = new int[len];
// Perform MergeSort operation
MergeSort(items, 0, len - 1, count);
List<int> res = new List<int>();
foreach(int i in count) { res.Add(i); }
return res;
}
// Function to sort the array
// using Merge Sort
public static void MergeSort(Item[] items, int low,
int high, int[] count)
{
// Base Case
if (low >= high) {
return;
}
// Find Mid
int mid = low + (high - low) / 2;
MergeSort(items, low, mid, count);
MergeSort(items, mid + 1, high, count);
// Merging step
Merge(items, low, mid, mid + 1, high, count);
}
// Utility function to merge sorted
// subarrays and find the count of
// greater elements on the right
public static void Merge(Item[] items, int low,
int lowEnd, int high,
int highEnd, int[] count)
{
int m = highEnd - low + 1; // mid
Item[] sorted = new Item[m];
int rightCounter = 0;
int lowInd = low, highInd = high;
int index = 0;
// Loop to store the count of
// larger elements on right side
// when both array have elements
while (lowInd <= lowEnd && highInd <= highEnd) {
if (items[lowInd].val < items[highInd].val) {
rightCounter++;
sorted[index++] = items[highInd++];
}
else {
count[items[lowInd].index] += rightCounter;
sorted[index++] = items[lowInd++];
}
}
// Loop to store the count of
// larger elements in right side
// when only left array have
// some element
while (lowInd <= lowEnd) {
count[items[lowInd].index] += rightCounter;
sorted[index++] = items[lowInd++];
}
// Loop to store the count of
// larger elements in right side
// when only right array have
// some element
while (highInd <= highEnd) {
sorted[index++] = items[highInd++];
}
Array.Copy(sorted, 0, items, low, m);
}
// Utility function that prints
// the count of greater elements
// on the right
public static void PrintArray(List<int> countList)
{
foreach(int i in countList)
{
Console.Write(i + " ");
}
Console.WriteLine();
}
// Driver Code
public static void Main(string[] args)
{
// Given array
int[] arr = { 3, 7, 1, 5, 9, 2 };
int n = arr.Length;
// Function Call
List<int> countList = CountLarge(arr);
PrintArray(countList);
}
}
// This code is contributed by akashish__
JavaScript
//Javascript equivalent
//Define an object Item
class Item {
constructor(val, index) {
this.val = val
this.index = index
}
}
//Function to count large elements
function countLarge(arr) {
// Length of the array
const length = arr.length
// Stores the index-value pairs
const items = []
for (let i = 0; i < length; i++) {
items.push(new Item(arr[i], i))
}
// Stores the count of greater elements on right
const count = []
for (let i = 0; i < length; i++) {
count.push(0)
}
// Perform MergeSort operation
mergeSort(items, 0, length - 1, count)
const res = count.slice(0)
return res
}
//Merge Sort function
function mergeSort(items, low, high, count) {
// Base Case
if (low >= high) return
// Find Mid
const mid = low + Math.floor((high - low) / 2)
mergeSort(items, low, mid, count)
mergeSort(items, mid + 1, high, count)
// Merging step
merge(items, low, mid, mid + 1, high, count)
}
//Merge function
function merge(items, low, lowEnd, high, highEnd, count) {
const mid = highEnd - low + 1 // mid
const sortedItems = []
for (let i = 0; i < mid; i++) {
sortedItems.push(null)
}
let rightCounter = 0
let lowInd = low
let highInd = high
let index = 0
// Loop to store the count of larger elements on right side
// when both array have elements
while (lowInd <= lowEnd && highInd <= highEnd) {
if (items[lowInd].val < items[highInd].val) {
rightCounter++
sortedItems[index] = items[highInd]
index++
highInd++
} else {
count[items[lowInd].index] += rightCounter
sortedItems[index] = items[lowInd]
index++
lowInd++
}
}
// Loop to store the count of larger elements in right side
// when only left array have elements
while (lowInd <= lowEnd) {
count[items[lowInd].index] += rightCounter
sortedItems[index] = items[lowInd]
index++
lowInd++
}
// Loop to store the count of larger elements in right side
// when only right array have elements
while (highInd <= highEnd) {
sortedItems[index] = items[highInd]
index++
highInd++
}
for (let i = 0; i < mid; i++) {
items[low + i] = sortedItems[i]
}
}
//Function to print array
function printArray(countList) {
let str = ''
for (let i = 0; i < countList.length; i++) {
str += countList[i] + ' '
}
console.log(str)
}
// Driver Code
// Given array
const arr = [3, 7, 1, 5, 9, 2]
// Function Call
const countList = countLarge(arr)
printArray(countList)
Time Complexity: O(N*log N)
Auxiliary Space: O(N)
Another approach: We can use binary search to solve this. The idea is to create a sorted list of input and then for each element of input we first remove that element from the sorted list and then apply the modified binary search to find the element just greater than the current element and then the number of large elements will be the difference between the found index & the length of sorted list.
C++
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
// Helper function to count the number of elements greater than 'item' in the sorted 'list'
int CountLargeNumbers(int item, vector<int>& list) {
int l=0;
int r=list.size()-1;
int mid = 0;
while(l<r){
mid = l + (r-l)/2;
if(list[mid] > item){
r = mid;
}
else{
l = mid + 1;
}
}
if(l==r && item > list[l]){
return 0;
}
return list.size()-l;
}
// Helper function to delete the first occurrence of 'item' from the sorted 'list'
void DeleteItemFromSortedList(vector<int>& list, int item) {
int index = lower_bound(list.begin(), list.end(), item) - list.begin();
list.erase(list.begin() + index);
}
// Function to count the number of elements greater than each element in the input list 'list'
vector<int> CountLarge(vector<int>& list) {
// Create a sorted copy of the input list
vector<int> sortedList = list;
sort(sortedList.begin(), sortedList.end());
// For each element in the input list, count the number of elements greater than it
for (int i = 0; i < list.size(); i++) {
DeleteItemFromSortedList(sortedList, list[i]);
list[i] = CountLargeNumbers(list[i], sortedList);
}
return list;
}
// Helper function to print the contents of a vector
void PrintArray(vector<int>& list) {
for (int i = 0; i < list.size(); i++) {
cout << list[i] << " ";
}
cout << endl;
}
// Main function
int main() {
// Create an input vector
vector<int> arr = {3, 7, 1, 5, 9, 2};
// Call the 'CountLarge' function to count the number of elements greater than each element in 'arr'
vector<int> res = CountLarge(arr);
// Print the result vector
PrintArray(res);
return 0;
}
Java
import java.util.*;
public class Main {
// Helper function to count the number of elements greater than 'item' in the sorted 'list'
public static int countLargeNumbers(int item, List<Integer> list) {
int l = 0;
int r = list.size() - 1;
int mid = 0;
while (l < r) {
mid = l + (r - l) / 2;
if (list.get(mid) > item) {
r = mid;
} else {
l = mid + 1;
}
}
if (l == r && item > list.get(l)) {
return 0;
}
return list.size() - l;
}
// Helper function to delete the first occurrence of 'item' from the sorted 'list'
public static void deleteItemFromSortedList(List<Integer> list, int item) {
int index = Collections.binarySearch(list, item);
if (index >= 0) {
list.remove(index);
}
}
// Function to count the number of elements greater than each element in the input list 'list'
public static List<Integer> countLarge(List<Integer> list) {
// Create a sorted copy of the input list
List<Integer> sortedList = new ArrayList<>(list);
Collections.sort(sortedList);
// For each element in the input list, count the number of elements greater than it
for (int i = 0; i < list.size(); i++) {
deleteItemFromSortedList(sortedList, list.get(i));
list.set(i, countLargeNumbers(list.get(i), sortedList));
}
return list;
}
// Helper function to print the contents of a list
public static void printList(List<Integer> list) {
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i) + " ");
}
System.out.println();
}
// Main function
public static void main(String[] args) {
// Create an input list
List<Integer> arr = new ArrayList<>(Arrays.asList(3, 7, 1, 5, 9, 2));
// Call the 'countLarge' function to count the number of elements greater than each element in 'arr'
List<Integer> res = countLarge(arr);
// Print the result list
printList(res);
}
}
Python3
def CountLarge(list):
sortedList = sorted(list)
for i in range(len(list)):
DeleteItemFromSortedList(sortedList, list[i])
list[i] = CountLargeNumbers(list[i], sortedList)
return list
def CountLargeNumbers(item, list):
l=0
r=len(list)-1
mid = 0
while(l<r):
mid = l + (r-l)//2
if(list[mid] > item):
r = mid
else:
l = mid + 1
if(l==r and item > list[l]):
return 0
return len(list)-l
def DeleteItemFromSortedList(list, item):
index = BinarySearch(list, item)
list.pop(index)
def BinarySearch(list, item):
l=0
r=len(list)-1
mid = 0
while(l<=r):
mid = l + (r-l)//2
if(list[mid] == item):
return mid
elif(list[mid] < item):
l = mid + 1
else:
r = mid - 1
return -1
def PrintArray(list):
for item in list:
print(item, end=" ")
arr = [3, 7, 1, 5, 9, 2]
res = CountLarge(arr)
PrintArray(res)
C#
using System;
using System.Collections.Generic;
public class GFG{
static public void Main (){
//Code
var arr = new List<int>(){3, 7, 1, 5, 9, 2};
var res = CountLarge(arr);
PrintArray(res);
}
public static List<int> CountLarge(List<int> list)
{
var sortedList = new List<int>(list);
sortedList.Sort();
for(int i=0;i<list.Count;i++){
DeleteItemFromSortedList(sortedList, list[i]);
list[i] = CountLargeNumbers(list[i], sortedList);
}
return list;
}
public static int CountLargeNumbers(int item, List<int> list){
int l=0,r=list.Count-1,mid;
while(l<r){
mid = l + (r-l)/2;
if(list[mid] > item)
r = mid;
else
l = mid + 1;
}
if(l==r && item > list[l])
return 0;
return list.Count-l;
}
public static void DeleteItemFromSortedList(List<int> list, int item){
var index = BinarySearch(list, item);
list.RemoveAt(index);
}
public static int BinarySearch(List<int> list, int item){
int l=0,r=list.Count-1,mid;
while(l<=r){
mid = l + (r-l)/2;
if(list[mid] == item)
return mid;
else if(list[mid] < item)
l = mid + 1;
else
r = mid - 1;
}
return -1;
}
public static void PrintArray(List<int> list)
{
foreach(var item in list)
Console.Write(item + " ");
}
}
JavaScript
<script>
function main() {
//Code
const arr = [3, 7, 1, 5, 9, 2];
const res = countLarge(arr);
printArray(res);
}
function countLarge(list) {
const sortedList = [...list];
sortedList.sort();
for (let i = 0; i < list.length; i++) {
deleteItemFromSortedList(sortedList, list[i]);
list[i] = countLargeNumbers(list[i], sortedList);
}
return list;
}
function countLargeNumbers(item, list) {
let l = 0;
let r = list.length - 1;
let mid;
while (l < r) {
mid = l + Math.floor((r - l) / 2);
if (list[mid] > item) r = mid;
else l = mid + 1;
}
if (l === r && item > list[l]) return 0;
return list.length - l;
}
function deleteItemFromSortedList(list, item) {
const index = binarySearch(list, item);
list.splice(index, 1);
}
function binarySearch(list, item) {
let l = 0;
let r = list.length - 1;
let mid;
while (l <= r) {
mid = l + Math.floor((r - l) / 2);
if (list[mid] === item) return mid;
else if (list[mid] < item) l = mid + 1;
else r = mid - 1;
}
return -1;
}
function printArray(list) {
for (const item of list) {
document.write(item + " ");
}
}
main();
</script>
Time Complexity: O(N^2)
Auxiliary Space: O(N)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem