LeetCode #315 Hard

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).

Constraints
  • 1 <= nums.length <= 10⁵
  • -10⁴ <= nums[i] <= 10⁴
arraymerge-sortdivide-and-conquer
Open on LeetCode ↗
02

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.

How to spot this pattern

"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.

03

Approach

Try it first

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?

1

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.

2

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.

3

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 j on.
  • Otherwise, including ties and an empty right half, place the left front and add j to the count at its index.

Ties go to the left because an equal value is not smaller.

4

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.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def countSmaller(self, nums: List[int]) -> List[int]:
▶3 counts = [0] * len(nums)
▶4 
▶5 def sort(items):
▶6 if len(items) <= 1:
▶7 return items
▶8 mid = len(items) // 2
▶9 left, right = sort(items[:mid]), sort(items[mid:])
▶10 merged, i, j = [], 0, 0
▶11 while i < len(left) or j < len(right):
▶12 if j < len(right) and (i == len(left) or right[j][0] < left[i][0]):
▶13 merged.append(right[j])
▶14 j += 1
▶15 else:
▶16 counts[left[i][1]] += j
▶17 merged.append(left[i])
▶18 i += 1
▶19 return merged
▶20 
▶21 sort([(value, i) for i, value in enumerate(nums)])
▶22 return counts
numscountsmergemerged5pos 002pos 106pos 201pos 30not startedemptycounts all 0 → sort (value, index) pairs
nums[5, 2, 6, 1]
counts[0, 0, 0, 0]
Every count starts at 0. Each value is paired with its index (its position, shown under it), because merge sort will move values around and a count must still land in the right slot.
numscountsmergemerged5pos 002pos 106pos 201pos 305pos 02pos 1leftright · 0 placedemptymerge [5] with [2]
left[5]sorted
right[2]sorted
j0
Both halves are sorted, and every value on the right started out after every value on the left. Merging them now finds, for each left value, the right values that are smaller.
numscountsmergemerged5pos 002pos 106pos 201pos 305pos 02pos 1leftright · 1 placed22 < 5 → place 2, j = 1
right front2
left front5
j1
2 is smaller than 5 and started out after it, so it is placed first. j becomes 1: every left value still waiting is larger than this value.
numscountsmergemerged5pos 012pos 106pos 201pos 305pos 02pos 1leftright · 1 placed25right half used up → place 5, counts[0] += 1
left front5index 0
j1right values placed
counts[0]1
The right half is used up, so 5 goes next. The 1 right value already placed is smaller and came after it: counts[0] grows by 1 to 1.
numscountsmergemerged5pos 012pos 106pos 201pos 306pos 21pos 3leftright · 0 placedemptymerge [6] with [1]
left[6]sorted
right[1]sorted
j0
Both halves are sorted, and every value on the right started out after every value on the left. Merging them now finds, for each left value, the right values that are smaller.
numscountsmergemerged5pos 012pos 106pos 201pos 306pos 21pos 3leftright · 1 placed11 < 6 → place 1, j = 1
right front1
left front6
j1
1 is smaller than 6 and started out after it, so it is placed first. j becomes 1: every left value still waiting is larger than this value.
numscountsmergemerged5pos 012pos 106pos 211pos 306pos 21pos 3leftright · 1 placed16right half used up → place 6, counts[2] += 1
left front6index 2
j1right values placed
counts[2]1
The right half is used up, so 6 goes next. The 1 right value already placed is smaller and came after it: counts[2] grows by 1 to 1.
numscountsmergemerged5pos 012pos 106pos 211pos 302pos 15pos 01pos 36pos 2leftright · 0 placedemptymerge [2, 5] with [1, 6]
left[2, 5]sorted
right[1, 6]sorted
j0
Both halves are sorted, and every value on the right started out after every value on the left. Merging them now finds, for each left value, the right values that are smaller.
numscountsmergemerged5pos 012pos 106pos 211pos 302pos 15pos 01pos 36pos 2leftright · 1 placed11 < 2 → place 1, j = 1
right front1
left front2
j1
1 is smaller than 2 and started out after it, so it is placed first. j becomes 1: every left value still waiting is larger than this value.
numscountsmergemerged5pos 012pos 116pos 211pos 302pos 15pos 01pos 36pos 2leftright · 1 placed122 < 6 → place 2, counts[1] += 1
left front2index 1
j1right values placed
counts[1]1
2 is not larger than the right front 6, so it is placed. The 1 right value already placed is smaller and came after it: counts[1] grows by 1 to 1.
numscountsmergemerged5pos 022pos 116pos 211pos 302pos 15pos 01pos 36pos 2leftright · 1 placed1255 < 6 → place 5, counts[0] += 1
left front5index 0
j1right values placed
counts[0]2
5 is not larger than the right front 6, so it is placed. The 1 right value already placed is smaller and came after it: counts[0] grows by 1 to 2.
numscountsmergemerged5pos 022pos 116pos 211pos 302pos 15pos 01pos 36pos 2leftright · 2 placed1256left half used up → place 6, j = 2
right front6
left frontnone
j2
The left half is used up, so 6 goes next. No left value is waiting, so nothing is counted.
numscountsmergemerged5pos 022pos 116pos 211pos 30done1256return [2, 1, 1, 0]
counts[2, 1, 1, 0]
Done. Each pair of positions met in exactly one merge, so every smaller value to the right of an element was added to its count exactly once.
05

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.

▶1class Solution:
▶2 def countSmaller(self, nums: List[int]) -> List[int]:
▶3 offset = 10**4 + 1
▶4 size = 2 * 10**4 + 1
▶5 tree = [0] * (size + 1)
▶6 counts = [0] * len(nums)
▶7 for i in range(len(nums) - 1, -1, -1):
▶8 pos = nums[i] + offset
▶9 k, below = pos - 1, 0
▶10 while k > 0:
▶11 below += tree[k]
▶12 k -= k & -k
▶13 counts[i] = below
▶14 while pos <= size:
▶15 tree[pos] += 1
▶16 pos += pos & -pos
▶17 return counts
06

Common pitfalls

Counting equal values as smaller

✗ Wrong
if j < len(right) and (i == len(left) or right[j][0] <= left[i][0]):
✓ Right
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

✗ Wrong
sort(nums)
✓ Right
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

✗ Wrong
counts[left[i][1]] += len(right)
✓ 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.

07

Complexity

Time
O(n log n)
Space
O(n)
The recursion has about log₂ n levels, and each level merges n elements in total. Space holds the pairs, the merged lists and the counts. The Fenwick tree version runs in O(n log V), where V = 20,001 is the number of possible values.
08

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).