You get an integer array nums. For every position i, count how many numbers after position i are strictly less than nums[i].
Return those counts as an array of the same length, where entry i belongs to nums[i].
Example 1
Input: nums = [7, 3, 8, 2, 3] Output: [3, 1, 2, 0, 0] Why: after 7 come 3, 2 and 3; after the first 3 only 2 is smaller
2 more examples and the constraints
Example 2
Input: nums = [-1] Output: [0] Why: nothing comes after the only number
Example 3
Input: nums = [4, 4, 4] Output: [0, 0, 0] Why: equal numbers are not smaller
Constraints
- 1 ≤ length of nums ≤ 100,000
- −10,000 ≤ nums[i] ≤ 10,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Check every pairO(n²)
- Fenwick tree from the rightO(n log V)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 100,000 numbers | Verdict |
|---|---|---|---|
| Check every pair | O(n²) | Too slow; about 5 billion checks | |
| Fenwick tree from the right | O(n log V) | Best; about 3 million steps |
n = length of nums, V = 20,001 possible values. A merge sort that counts right-side numbers passing to the left also runs in O(n log n).
Edge cases to test
- One number. [−1] gives [0]: nothing comes after it.
- Equal numbers. [4, 4, 4] gives all zeros, because equal is not smaller.
- Negative values. Shift by 10,001 so every value maps to an index of at least 1.
- Sorted from high to low. [4, 3, 2, 1] gives [3, 2, 1, 0], the largest counts possible.
Common mistakes
- Counting equal numbers as smaller by summing up to nums[i] instead of nums[i] − 1.
- Adding nums[i] to the tree before querying, so it counts itself.
- Using a value as a Fenwick index without shifting, so 0 and negative values break the loop.
How to talk through it
- 1Clarify. Strictly smaller, or smaller or equal? What range can the values take? How long is the array?
- 2Give the brute force. Two loops over all pairs, O(n²), too slow at 100,000.
- 3Change the direction. From the right, the numbers already seen are exactly the ones after i, so the question becomes a count of seen values below nums[i].
- 4Pick the structure. That is a prefix sum over value counts with updates: a Fenwick tree does both in O(log V).
- 5Test out loud. Run [−1], [4, 4, 4], a falling array and Example 1 before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?