Stacks and Queues Monotonic stack
221. Number of Greater Elements to the Right
You are given an array of integers nums and an array of indices queries. For each query i, count the
elements that come after position i in nums and are strictly greater than nums[i].
Return an array with one count per query, in the same order as queries.
"After position i" means every position from i + 1 to the end of the array, not only the next one. An
element equal to nums[i] does not count. Indices start at 0.
Example 1
Input: nums = [4, 9, 2, 7, 5, 9, 1], queries = [0, 2, 4, 6]
[4,3,1,0]Explanation: After index 0 (value 4), the values 9, 7, 5 and 9 are greater. After index 2 (value 2), 7, 5 and 9 are greater. After index 4 (value 5), only 9 is. Index 6 is the last one, so nothing comes after it.
Example 2
Input: nums = [-3, -3, 0, -3, 0], queries = [0, 1, 3, 4]
[2,2,1,0]Explanation: For each -3, only the zeros after it count. The other -3 values are equal, not greater.
Example 3
Input: nums = [1, 2, 3, 4], queries = [3, 0, 0, 2]
[0,3,3,1]Explanation: Queries can repeat and come in any order, and each one gets its own answer in its own place.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ nums.length ≤ 105-109 ≤ nums[i] ≤ 1091 ≤ queries.length ≤ 1050 ≤ queries[i] < nums.length
Clarifying questions
What you would ask an interviewer before writing any code.