Count of Smaller Numbers After Self solution explained
Count of Smaller Numbers After Self asks, for every position in an array, how many later elements are strictly smaller. Walk the array from right to left and keep a Fenwick tree (binary indexed tree) of the values seen so far, indexed by each value's rank in sorted order: for each element, query how many seen values rank below it, then add it. That takes O(n log n) time and O(n) memory; a merge sort that counts elements jumping from the right half to the left half gives the same bound.
By Evin JohnPublished 7 min read
The problem, restated
You get an array of integers, possibly negative and possibly repeated. Return a new array of the same length where each entry counts how many elements to the right of that position are strictly smaller than the element at that position.
| Input | Output | Note |
|---|---|---|
| [4, 9, 2, 9, 1] | [2, 2, 1, 1, 0] | The second 9 does not count against the first one |
| [-2, 7, -2, 0] | [0, 2, 0, 0] | Negatives and a repeated value |
| [6, 5, 4] | [2, 1, 0] | Strictly falling: each entry counts everything after it |
| [1, 2, 3] | [0, 0, 0] | Strictly rising |
| [3, 3, 3] | [0, 0, 0] | Equal values never count |
What the interviewer is testing
The double loop is obvious, so the interview is about what comes after. Interviewers want to hear you recognize a counting-over-order problem, the same family as counting inversions, and pick a structure that answers "how many of the values I have seen are below x?" in logarithmic time. Knowing the Fenwick tree well enough to write it from memory is a plus, and so is being able to explain the merge sort alternative and how it tracks original positions.
Follow-ups
- Count larger numbers before each position instead. Scan left to right and query the count above the current rank.
- Total inversions only. Sum the output, or let merge sort add up its jumps without per-element bookkeeping.
- Values are known to be small, like 0 to 100. Skip compression and index the tree directly by value.
- Count values in a range after each position. Two prefix queries on the same tree.
Brute force
def count_smaller_slow(nums):
n = len(nums)
return [sum(1 for j in range(i + 1, n) if nums[j] < nums[i]) for i in range(n)]A tempting middle step keeps a sorted list of the elements seen from the right and uses binary search to find where each new element would go. The search is O(log n), but inserting into a Python list or JavaScript array shifts elements, which is O(n) in the worst case. Mention it as a practical speed-up, not as the answer.
Fenwick tree over value ranks
Scan from the right. At each position, the elements already seen are exactly the elements after it. If we keep a count of how many seen elements hold each value, the answer for the position is the sum of counts for all smaller values: a prefix sum. A Fenwick tree supports both "add 1 at index k" and "sum of indexes 1 to k" in O(log n).
Values can be negative or large, so first replace each value with its rank among the distinct values, starting at 1. For an element with rank r, the count of strictly smaller seen values is the prefix sum up to r - 1. Equal values have equal ranks, so they are not counted, which is what the problem asks.
def count_smaller(nums):
ranks = {v: i + 1 for i, v in enumerate(sorted(set(nums)))}
size = len(ranks)
tree = [0] * (size + 1)
def add(i):
while i <= size:
tree[i] += 1
i += i & -i
def prefix(i):
total = 0
while i > 0:
total += tree[i]
i -= i & -i
return total
result = [0] * len(nums)
for i in range(len(nums) - 1, -1, -1):
r = ranks[nums[i]]
result[i] = prefix(r - 1)
add(r)
return resultfunction countSmaller(nums) {
const sorted = Array.from(new Set(nums)).sort((a, b) => a - b);
const rank = new Map();
sorted.forEach((v, i) => rank.set(v, i + 1));
const size = sorted.length;
const tree = new Array(size + 1).fill(0);
const add = (i) => {
for (; i <= size; i += i & -i) tree[i] += 1;
};
const prefix = (i) => {
let total = 0;
for (; i > 0; i -= i & -i) total += tree[i];
return total;
};
const result = new Array(nums.length).fill(0);
for (let i = nums.length - 1; i >= 0; i--) {
const r = rank.get(nums[i]);
result[i] = prefix(r - 1);
add(r);
}
return result;
}Trace [4, 9, 2, 9, 1]. The distinct values sorted are 1, 2, 4, 9, so the ranks are 1, 2, 3, 4. From the right: 1 has rank 1, nothing below, answer 0, add rank 1. 9 has rank 4, prefix(3) = 1, answer 1. 2 has rank 2, prefix(1) = 1, answer 1. The first 9 has rank 4, prefix(3) = 2 (the 1 and the 2; the other 9 sits at rank 4), answer 2. 4 has rank 3, prefix(2) = 2, answer 2. Output [2, 2, 1, 1, 0].
Without a comparator function, JavaScript's sort compares numbers as strings, so 10 would be placed before 9. The ranks would then be wrong in a way that only some inputs reveal.
Merge sort alternative
Sort the indexes by value with merge sort. When merging two sorted halves, every element of the right half that is placed before an element of the left half is a later element that is smaller. So when a left element is placed, add the number of right elements already placed to its count. Taking from the left on ties keeps equal values from counting.
def count_smaller_merge(nums):
counts = [0] * len(nums)
def sort(idx):
if len(idx) <= 1:
return idx
mid = len(idx) // 2
left, right = sort(idx[:mid]), sort(idx[mid:])
merged, j = [], 0
for i in left:
while j < len(right) and nums[right[j]] < nums[i]:
merged.append(right[j])
j += 1
counts[i] += j
merged.append(i)
merged.extend(right[j:])
return merged
sort(list(range(len(nums))))
return countsComplexity
| Approach | Time | Extra memory |
|---|---|---|
| Double loop | O(n²) | O(1) beyond the output |
| Sorted list with binary search and insertion | O(n²) worst case, often fast in practice | O(n) |
| Fenwick tree with rank compression | O(n log n) | O(n) |
| Merge sort over indexes | O(n log n) | O(n) |
Edge cases
- Empty array: empty output. One element: [0].
- All values equal: all zeros, which tests the strictly-smaller rule.
- Negative values and zero, which break direct value indexing without compression.
- Strictly falling arrays, the worst case for any approach that relies on few inversions.
- Very large values, which are fine after compression but would overflow a value-indexed array.
Common mistakes
- Querying prefix(r) instead of prefix(r - 1), which counts equal values.
- Scanning left to right, which counts elements before each position.
- Sorting values in the merge sort and losing track of where each one came from; sort indexes instead.
- Taking from the right on ties during merging, which counts equal values as smaller.
- Forgetting a numeric comparator in JavaScript.
How to explain it out loud
Fictional example
- Candidate
- If I walk from the right, everything I have already seen is to the right of the current position. So I need a structure that tells me how many seen values are below x, and lets me add values as I go.
- Candidate
- Values can be negative or large, so I map them to ranks first. Then a Fenwick tree over ranks gives prefix counts and single additions in log time each. The answer for rank r is the prefix up to r minus 1, so equal values are excluded.
- Candidate
- That is O(n log n). An alternative is merge sort over indexes, where each left element counts how many right elements jumped ahead of it.
Related problems
Kth Missing Positive Number is another problem where counting below a position by binary search replaces a linear walk. Maximal Rectangle also replaces a quadratic scan with a structure that processes each element a constant number of times. Merge k Sorted Lists is a good place to practice the merging step on its own, and Top K Frequent Elements uses counting with a different goal.
Practicing with Natively
Writing a Fenwick tree from memory is a small skill that pays off in several hard problems, so drill it until the two loops come out right. When you practice on Mac or Windows, Natively can read a problem from a screenshot and suggest an approach to compare with your own after you have tried it, and a transcript of the mock round shows whether you explained the rank step clearly. See the AI interview assistant.
Questions people ask
How do you solve Count of Smaller Numbers After Self?
Map values to ranks, scan from right to left, and for each element ask a Fenwick tree how many seen values have a lower rank, then add the element's rank to the tree.
Can I use merge sort for Count of Smaller Numbers After Self?
Yes. Sort indexes by value with merge sort; when a left-half element is placed, add the number of right-half elements already placed before it.
What is the time complexity?
O(n log n) time and O(n) memory for both the Fenwick tree and merge sort versions. The double loop is O(n squared).
Do equal values count as smaller?
No. Query the prefix up to rank minus 1 in the Fenwick tree, and take from the left half on ties in merge sort.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
