Count of Smaller Numbers After Self
Count of Smaller Numbers After Self is LeetCode 315 (Hard). Given an integer array nums, return an array counts where counts[i] is how many elements to the right of nums[i] are strictly smaller than it.
- Equal values do not count.
- GeeksforGeeks has the same task under the name Count Smaller Elements on Right Side.
With up to 10⁵ elements, checking every later element for every index takes about 5 × 10⁹ comparisons, far too slow. The answer needs O(n log n).
- 1 <= nums.length <= 10⁵
- -10⁴ <= nums[i] <= 10⁴
Intuition
Merge sort already compares elements from the two halves of the array, and it can count while it does so.
When two sorted halves merge, every element of the right half started out after every element of the left half. So when a left element is placed, the right elements already placed ahead of it are exactly the ones that are smaller and later. Their number, j, is what that element adds to its count.
Pairs that sit inside one half are counted when that half is sorted, deeper in the recursion, so every pair is counted exactly once.
"For each element, how many later elements are smaller" is a per-element version of counting inversions. Merge sort counts pairs that cross the middle while it merges; a Fenwick tree over the values does the same from right to left.
Approach
Before reading on: merge the sorted halves [2, 5] and [1, 6]. At the moment 5 is placed, which right-half values are already in front of it, and why are they exactly the smaller values after 5?
Two ways to solve it
Sort (value, index) pairs and count, while merging, the right elements placed before each left one.
- Values: any range; no shifting needed.
- Code: the merge step of a normal merge sort.
- Idea: the same as counting inversions.
Works for any input without extra setup.
Walk from right to left, ask how many seen values are below the current one, then add it.
- Values: shifted to positions 1 to V.
- Code: two short loops.
- Idea: prefix counts over values.
Shorter, when the value range is small.
Both are fast enough for 10⁵ elements; merge sort does not depend on the value range, so the steps, code and live demo below use it. The Fenwick tree version is shorter once you know the structure, and its code comes after the demo.
Pair each value with its index
Sort (value, index) pairs instead of bare values. Merge sort moves elements around, and the stored index tells you which answer slot a count belongs to.
Sort both halves first
Split the list in the middle and sort each half recursively; a list of one element is already sorted. When both calls return, every pair inside one half has been counted, and both halves are in sorted order.
Merge, placing the smaller front element
Walk both halves with i and j and place one element per step:
- If the right front is strictly smaller than the left front, place it and move
jon. - Otherwise, including ties and an empty right half, place the left front and add
jto the count at its index.
Ties go to the left because an equal value is not smaller.
Return the counts
After the top-level merge, each element has collected the smaller elements from every half it was merged with, so counts is the answer.
Code in Python, C++ and Java
j becomes 1: every left value still waiting is larger than this value.counts[0] grows by 1 to 1.j becomes 1: every left value still waiting is larger than this value.counts[2] grows by 1 to 1.j becomes 1: every left value still waiting is larger than this value.counts[1] grows by 1 to 1.counts[0] grows by 1 to 2.j becomes 1: every left value still waiting is larger than this value.counts[3] grows by 1 to 1.j becomes 1: every left value still waiting is larger than this value.counts[2] grows by 1 to 1.j becomes 1: every left value still waiting is larger than this value.j becomes 2: every left value still waiting is larger than these 2 values.j becomes 3: every left value still waiting is larger than these 3 values.counts[1] grows by 3 to 3.Fenwick tree over values
Walk from right to left. The values lie between -10⁴ and 10⁴, so adding 10⁴ + 1 turns each one into a position from 1 to 20,001. For each element, a Fenwick tree (binary indexed tree) query counts the seen values at positions below it, which are the smaller values to its right; then the element's own position is added.
Common pitfalls
Counting equal values as smaller
if j < len(right) and (i == len(left) or right[j][0] <= left[i][0]):
if j < len(right) and (i == len(left) or right[j][0] < left[i][0]):
With <=, an equal right value is placed first and then counted for the left one. [-1, -1] returns [1, 0] instead of [0, 0].
Sorting bare values
sort(nums)
sort([(value, i) for i, value in enumerate(nums)])
After a few merges a value no longer sits at its starting position, and with duplicates you cannot tell which copy it is. The stored index says where its count goes.
Adding the whole right half
counts[left[i][1]] += len(right)
counts[left[i][1]] += j
Only the right elements already placed are smaller than this left element. The rest of the right half is larger or equal; for [2, 5] merged with [1, 6], 2 would get 2 instead of 1.
Complexity
Count of Smaller Numbers After Self FAQ
How is this different from counting inversions?
An inversion is a pair i < j with nums[i] > nums[j]. Count Inversions asks for the total number of such pairs; this problem asks how many each element starts. The merge is the same, but here the count is added to the left element's own slot instead of one running total, which is why every value carries its index.
Can I insert into a sorted list with binary search instead?
Walk from right to left, use binary search to find how many seen values are smaller, then insert the value. The search is O(log n), but inserting into a Python list or array shifts elements, so the worst case is O(n²). It often passes in Python because the shift is fast memory movement, but it is not O(n log n).