VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-smaller-elements-on-right-side/

⇱ Count smaller elements on Right side - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count smaller elements on Right side

Last Updated : 12 Nov, 2025

Given an unsorted array arr[] of distinct integers, construct another array countSmaller[] such that countSmaller[i] contains the count of smaller elements on the right side of each element arr[i] in the array.

Examples: 

Input: arr[] =  [12, 1, 2, 3, 0, 11, 4]
Output: [6, 1, 1, 1, 0, 1, 0]

Input: arr[] = [5, 4, 3, 2, 1]
Output: [4, 3, 2, 1, 0]

Input: arr[] =  [1, 2, 3, 4, 5]
Output: [0, 0, 0, 0, 0]

[Naive Approach] Using Nested Loop - O(n*n) Time and O(n) Space

The idea is to use nested loops, where for each element we check how many elements on its right side are smaller than it.


Output
6 1 1 1 0 1 0 

[Expected Approach] Using Merge Sort - O(nlogn) Time and O(n) Space

The idea is to use a modified merge sort. We store both element values and their original indices. While merging, we count how many elements from the right half are smaller and add this count to the corresponding index’s result.

Steps to solve the problem:

  • Store each element with its index in a pair (value, index).
  • Perform merge sort on this pair array.
  • During merging: check if a left element is greater than a right element.
  • If yes, then all remaining elements in the right half are smaller → add their count to the result of that left element’s index.
  • After counting, place elements into the merged array.
  • Otherwise, merge normally when the left element is not greater.
  • Continue recursively until the entire array is sorted.
  • The result array will finally hold the number of smaller elements on the right for each index.

Output
6 1 1 1 0 1 0 
Comment
Article Tags: