oneby7

Stacks and Queues Monotonic stack

221. Number of Greater Elements to the Right

Medium

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]

Output: [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]

Output: [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]

Output: [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.

nums = [5, 1, 5, 6, 5], queries = [0]

Constraints

  • 1 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109
  • 1 ≤ queries.length ≤ 105
  • 0 ≤ queries[i] < nums.length

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.