Count of Smaller Numbers After Self
Hard
Topics
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
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
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
- Compress the values to ranks
1..kso they can index a Binary Indexed Tree. Sorting the distinct values and binary searching gives the rank. - Walk
ifromn - 1down to 0. Everything in the tree at that moment sits strictly to the right ofi. - Query the prefix sum over ranks strictly below
rank[i]— that count iscounts[i]. - Insert
rank[i]into the tree and continue. - 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 countsDry 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, notrank. 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 & -iloop 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 countsimport java.util.*;
class Solution {
private int k;
private int[] tree;
private void add(int i) {
while (i <= k) {
tree[i]++;
i += i & -i;
}
}
private int query(int i) {
int total = 0;
while (i > 0) {
total += tree[i];
i -= i & -i;
}
return total;
}
public int[] countSmaller(int[] nums) {
int n = nums.length;
int[] order = nums.clone();
Arrays.sort(order);
int distinct = 0;
for (int i = 0; i < n; i++) {
if (i == 0 || order[i] != order[i - 1]) order[distinct++] = order[i];
}
k = distinct;
tree = new int[k + 1];
int[] counts = new int[n];
for (int i = n - 1; i >= 0; i--) {
int lo = 0, hi = distinct - 1, r = 0;
while (lo <= hi) {
int mid = (lo + hi) >>> 1;
if (order[mid] < nums[i]) lo = mid + 1;
else { r = mid + 1; hi = mid - 1; }
}
counts[i] = query(r - 1);
add(r);
}
return counts;
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
int k;
vector<int> tree;
void add(int i) {
while (i <= k) {
tree[i]++;
i += i & -i;
}
}
int query(int i) {
int total = 0;
while (i > 0) {
total += tree[i];
i -= i & -i;
}
return total;
}
public: vector<int> countSmaller(vector<int>& nums) {
int n = (int)nums.size();
vector<int> order(nums);
sort(order.begin(), order.end());
order.erase(unique(order.begin(), order.end()), order.end());
k = (int)order.size();
tree.assign(k + 1, 0);
vector<int> counts(n, 0);
for (int i = n - 1; i >= 0; i--) {
int r = (int)(lower_bound(order.begin(), order.end(), nums[i]) - order.begin()) + 1;
counts[i] = query(r - 1);
add(r);
}
return counts;
}
};/**
* @param {number[]} nums
* @return {number[]}
*/ var countSmaller = function(nums) {
const n = nums.length;
const order = [...new Set(nums)].sort((a, b) => a - b);
const rank = new Map();
for (let i = 0; i < order.length; i++) rank.set(order[i], i + 1);
const k = order.length;
const tree = new Array(k + 1).fill(0);
const add = (i) => {
while (i <= k) {
tree[i]++;
i += i & -i;
}
};
const query = (i) => {
let total = 0;
while (i > 0) {
total += tree[i];
i -= i & -i;
}
return total;
};
const counts = new Array(n).fill(0);
for (let i = n - 1; i >= 0; i--) {
const r = rank.get(nums[i]);
counts[i] = query(r - 1);
add(r);
}
return counts;
};