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^4See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI