Count of Smaller Numbers After Self (LeetCode 315): Solution and Explanation

Hard
Array
Binary Indexed Tree
Segment Tree
Divide And Conquer
Merge Sort

For each element of an integer array, count how many elements to its right are strictly smaller than it. Return those counts as an array aligned with the input.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

The brute force checks every pair: for each index, scan everything to its right and count smaller values. That is O(n²) comparisons, which is too slow when the array has a hundred thousand elements.

Notice that the question for index i only concerns elements after i. If you walk the array from right to left, then at the moment you reach nums[i] you have already seen exactly the elements to its right and nothing else. So keep everything seen so far in a structure that can answer "how many values are smaller than x" quickly.

A sorted list is the simplest such structure. Binary search with bisect_left returns the position where x would be inserted to the left of any equal values, and that position is precisely the number of stored values strictly smaller than x. After answering, insert x into the sorted list so it counts for elements further left. The answers come out in reverse order, so flip them at the end.

One honest caveat: inserting into the middle of a Python list shifts elements, so each insertion is linear in the worst case. The shift is a fast memory move and usually performs well, but the asymptotic bound is quadratic. A Fenwick tree or a merge-sort count gives a true O(n log n) if you need it.

Approach: Reverse scan with a sorted list and binary search

  1. Create empty lists result and sorted_list.
  2. Iterate over nums in reverse order.
  3. For each num, compute idx = bisect_left(sorted_list, num), the count of stored values strictly smaller than num.
  4. Append idx to result.
  5. Insert num into sorted_list at its sorted position with insort.
  6. Return result[::-1] so the counts line up with the original indices.

Step-by-step example

nums = [5, 2, 6, 1]
  1. Start from the right with 1. The sorted list is empty, so the count is 0. The list becomes [1].
  2. Next 6: bisect_left([1], 6) = 1, so one smaller value. The list becomes [1, 6].
  3. Next 2: bisect_left([1, 6], 2) = 1, just the 1. The list becomes [1, 2, 6].
  4. Next 5: bisect_left([1, 2, 6], 5) = 2, counting 1 and 2. The list becomes [1, 2, 5, 6].
  5. result is [0, 1, 1, 2], and reversing it gives the answer [2, 1, 1, 0].

Code: Python, Java, C++

1class Solution:
2    def countSmaller(self, nums: List[int]) -> List[int]:
3        from bisect import bisect_left, insort
4        result = []
5        sorted_list = []
6
7        for num in reversed(nums):
8            # Count of elements strictly smaller than num so far
9            idx = bisect_left(sorted_list, num)
10            result.append(idx)
11            insort(sorted_list, num)
12
13        return result[::-1]

Time and space complexity

Time

O(n²) worst case

Each binary search is O(log n), but insort must shift elements to make room, which is O(n) per insertion in the worst case. In practice the shift is a fast block copy, so this runs well on typical inputs.

Space

O(n)

The sorted list and the result list each hold n values.

Other approaches

Fenwick tree over ranks (time O(n log n), space O(n))

Compress values to ranks 1 through k, scan from the right, query the prefix sum of ranks below the current one, then add 1 at its rank. Every operation is logarithmic.

Merge sort with counting (time O(n log n), space O(n))

Sort indices by value with merge sort; while merging, every element taken from the left half gains the number of right-half elements already placed, which are smaller and originally to its right.

Common mistakes

  • Using bisect_right instead of bisect_left. That counts equal values as smaller, but the problem asks for strictly smaller elements.
  • Scanning left to right, which counts elements before the index instead of after it.
  • Forgetting to reverse result at the end, so the counts come out mirrored.
  • Assuming the sorted list approach is O(n log n). The binary search is logarithmic, but list insertion is linear, so the strict bound is O(n²).

Frequently asked questions

What is the best approach for count of smaller numbers after self?

For a guaranteed O(n log n), use a Fenwick tree over compressed values or merge sort with counting. A reverse scan with a sorted list and binary search is the shortest code and fast in practice.

Why scan the array from right to left?

Every value already processed is to the right of the current index, so the data structure holds exactly the elements the question asks about.

Why bisect_left and not bisect_right?

bisect_left places the insertion point before any equal values, so its index counts only values strictly smaller than the target. bisect_right would also count duplicates.

How does merge sort solve this problem?

During each merge, the right half holds elements that were originally to the right. When a left element is placed, the number of right elements already placed are all smaller, and that number is added to its count.