SDE & MLE Prep

315. Count of Smaller Numbers After Self

Problem

For each nums[i], count how many elements to its right are strictly smaller, and return these counts.

Example: [5,2,6,1] → [2,1,1,0]

Constraints: n ≤ 10⁵.

Scan from the right. Compress values to ranks 1..m; a Fenwick tree counts how many already-seen (i.e. to the right) values have a smaller rank: query(rank − 1), then add(rank, 1).

nums 5 2 6 1        ranks 3 2 4 1
i=3 (1): seen {}        smaller 0   add rank1
i=2 (6): seen {1}       smaller 1   add rank4
i=1 (2): seen {1,6}     smaller 1   add rank2
i=0 (5): seen {1,6,2}   smaller 2   -> [2, 1, 1, 0]

Complexity: O(n log n).

class Solution:
    def countSmaller(self, nums: List[int]) -> List[int]:
        rank = {v: i + 1 for i, v in enumerate(sorted(set(nums)))}
        t = [0] * (len(rank) + 1)
        res = []
        for x in reversed(nums):
            i, s = rank[x] - 1, 0
            while i:
                s += t[i]
                i -= i & -i
            res.append(s)
            i = rank[x]
            while i < len(t):
                t[i] += 1
                i += i & -i
        return res[::-1]