Count of Smaller Numbers After Self

Hard

Topics
ArrayBinary Indexed TreeSegment TreeMerge SortDivide and Conquer

Given an integer array nums, return an array counts where counts[i] is the number of elements to the right of nums[i] that are smaller than nums[i].

Example 1

50216213
Input:  nums = [5,2,6,1]
Output: [2,1,1,0]
Explanation: To the right of 5 are 2 and 1; to the right of 2 is 1; to the right of 6 is 1; nothing is right of 1.

Example 2

-10-11
Input:  nums = [-1,-1]
Output: [0,0]

Constraints

  • 1 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
Editorial — intuition, approach, complexity and pitfalls

Intuition

This is an inversion-counting problem. The trick is to process values in an order that makes "how many smaller things have I already seen to the right" a single query. Sweeping right to left with a Binary Indexed Tree over the value axis does exactly that: at index i, everything already inserted lies to the right, so a prefix-sum query below nums[i] is the answer. Merge sort reaches the same result by counting how many elements jump left during each merge.

Approach

  1. Compress the values to ranks 1..k so they can index a Binary Indexed Tree. Sorting the distinct values and binary searching gives the rank.
  2. Walk i from n - 1 down to 0. Everything in the tree at that moment sits strictly to the right of i.
  3. Query the prefix sum over ranks strictly below rank[i] — that count is counts[i].
  4. Insert rank[i] into the tree and continue.
  5. The merge-sort alternative sorts index-value pairs and, whenever an element from the right half is taken before elements remain in the left half, credits those left-half elements with one inversion each.
class Solution:
    def countSmaller(self, nums):
        order = sorted(set(nums))
        rank = {v: i + 1 for i, v in enumerate(order)}
        k = len(order)
        tree = [0] * (k + 1)

        def add(i):
            while i <= k:
                tree[i] += 1
                i += i & -i

        def query(i):
            total = 0
            while i > 0:
                total += tree[i]
                i -= i & -i
            return total

        counts = [0] * len(nums)
        for i in range(len(nums) - 1, -1, -1):
            r = rank[nums[i]]
            counts[i] = query(r - 1)
            add(r)
        return counts

Dry Run

nums = [5, 2, 6, 1]
Compress first: the sorted distinct values are [1, 2, 5, 6], so
rank = {1:1, 2:2, 5:3, 6:4} and k = 4. Ranks are 1-based because a BIT index of 0
would make i += i & -i loop forever.
Sweep right to left. Everything already in the tree lies strictly to the right of i,
so query(rank - 1) answers "how many of those are smaller".
  i=3  nums=1  rank 1  query(0) reads nothing            = 0  add(1) bumps 1,2,4
                                               tree = [1, 1, 0, 1]   counts [0,0,0,0]
  i=2  nums=6  rank 4  query(3) reads tree[3]+tree[2]
                                     = 0 + 1            = 1  add(4) bumps 4
                                               tree = [1, 1, 0, 2]   counts [0,0,1,0]
  i=1  nums=2  rank 2  query(1) reads tree[1]            = 1  add(2) bumps 2,4
                                               tree = [1, 2, 0, 3]   counts [0,1,1,0]
  i=0  nums=5  rank 3  query(2) reads tree[2]            = 2  add(3) bumps 3,4
                                               tree = [1, 2, 1, 4]   counts [2,1,1,0]
answer 2 1 1 0
Two things to notice. query(3) reads two cells rather than three: i -= i & -i walks
a prefix down in O(log k) jumps, and i += i & -i bumps exactly the cells whose
ranges cover the inserted rank. And tree[3] is still 0 when i=2 reads it -- rank 3
is the value 5, which sits to the LEFT of index 2 and has not been inserted yet.
That is the sweep direction doing its job.
The strict bound is load-bearing. Change query(r - 1) to query(r) and equal values
start counting each other: on nums = [4,-4,-1,-4,2,2,2,5,1] the correct answer is
7 0 1 0 1 1 1 1 0 but query(r) returns 7 1 1 0 3 2 1 1 0.

Complexity

  • Time — O(n log n) — one BIT insert and one query per element.
  • Space — O(n) for the rank map and the tree.

Common Pitfalls

  • Query rank - 1, not rank. Including the element's own rank counts equal values, which the problem excludes.
  • The sweep must go right to left. Left to right counts smaller elements before each index, which is a different quantity.
  • BIT indices are 1-based; a rank of 0 makes i += i & -i loop forever.
  • Values can be negative, so coordinate-compress rather than using values as array indices directly.
  • The naive O(n^2) double loop is correct but will time out at n = 10^5 — interviewers ask for this problem precisely to see the log-factor structure.

Full Solution — all languages

class Solution:
    def countSmaller(self, nums):
        order = sorted(set(nums))
        rank = {v: i + 1 for i, v in enumerate(order)}
        k = len(order)
        tree = [0] * (k + 1)
        def add(i):
            while i <= k:
                tree[i] += 1
                i += i & -i
        def query(i):
            total = 0
            while i > 0:
                total += tree[i]
                i -= i & -i
            return total
        counts = [0] * len(nums)
        for i in range(len(nums) - 1, -1, -1):
            r = rank[nums[i]]
            counts[i] = query(r - 1)
            add(r)
        return counts
SensAI
Beta
Tap the mic to stop voice mode