Count of Smaller Numbers After Self
1 approach, code in every language
Problem description
For each position in an integer array, determine how many values located strictly to its right are smaller than the value at that position. Return these tallies as an array aligned with the original positions.
A brute-force double loop is quadratic, which is too slow for large inputs. Processing the array from right to left while maintaining an order-statistics structure lets each query answer 'how many already-seen values are smaller' in logarithmic time.
Example 1
Input: nums = [5,2,6,1]
Output: [2,1,1,0]
To the right of 5 there are two smaller values (2 and 1); to the right of 2 there is one (1); to the right of 6 there is one (1); and the last element has nothing after it.
Example 2
Input: nums = [-1,-1]
Output: [0,0]
Neither element has a strictly smaller value to its right.
Constraints
1 ≤ nums.length ≤ 10^5-10^4 ≤ nums[i] ≤ 10^4
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Cooler Gauges Downstream is our own problem on the technique behind Count of Smaller Numbers After Self: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free