Count of Smaller Numbers After Self

HardRange Query · Fenwick Tree (BIT)🧩 Fenwick & Segment TreeLeetCode #315 ↗Updated

Problem

You are given an integer array nums. Build and return a list counts of the same length where counts[i] is how many elements to the right of index i are strictly smaller than nums[i].
Inputnums = [5,2,6,1]Output[2,1,1,0]
Inputnums = [-1]Output[0]
Inputnums = [-1,-1]Output[0,0]

1 ≤ n ≤ 105  ·  -104 ≤ nums[i] ≤ 104

Try it yourself

Java
class Solution {
    public List<Integer> countSmaller(int[] nums) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Walk the array right to left: everything already seen is exactly the “after self” part. Store seen values as frequencies by rank in a Fenwick tree, and the answer for nums[i] is a single prefix-sum query over smaller ranks.
PatternFenwick & Segment Tree

Instinct Range sums, mins or counts asked again and again while values keep changing: prefix sums break, so reach for a Fenwick or segment tree.

Memory hack Prefix sums freeze, trees breathe: climb by the last set bit (i & -i) for Fenwick, split in halves for segment trees.

Open the Fenwick & Segment Tree guide →

Approaches

Brute ForceCompare Every Pair

Time O(n²)Space O(1) extra

For each index i, scan every j > i and count the values below nums[i]. This is the definition turned straight into two loops.

Java
public List<Integer> countSmaller(int[] nums) {
    int n = nums.length;
    List<Integer> res = new ArrayList<>(n);
    for (int i = 0; i < n; i++) {
        int cnt = 0;
        for (int j = i + 1; j < n; j++) {
            if (nums[j] < nums[i]) cnt++;
        }
        res.add(cnt);
    }
    return res;
}

Obviously correct, but ~5·109 comparisons at n = 105.

At a glance

LevelApproachTimeSpace
Brute ForceCompare Every PairO(n²)O(1) extra
BetterSorted Suffix + Binary Search InsertionO(n²) worst (O(n log n) compares)O(n)
OptimalFenwick Tree over Value RanksO(n log n)O(n)
Common pitfalls
  • Counting smaller or equal — query rank - 1, not the rank itself.
  • Scanning left to right — then the tree holds the prefix, not the elements after self.
  • Negative values used directly as Fenwick indices — compress or offset first.
Interview tips
  • Reframe it: “for each element, count smaller among the ones already processed”.
  • Explain why the sorted-list idea is still quadratic (insert shifts), motivating the BIT.
  • Mention merge sort with index tracking as an equally valid O(n log n) alternative.
Pattern
Fenwick tree on ranks → online “how many seen values are smaller/larger” counts, i.e. inversion-style problems.
My notes saved in this browser