awelgorithms

Next greater to the right

Updated

Next greater of i is the first j > i with a[j] > a[i], or none. Scan left to right with a decreasing index stack. For each i, pop while a[top] < a[i]; each popped index just found i as its next greater. Then push i. Leftovers at the end have none.

What to focus on

Write answers at pop time. Strictly greater: equal values do not pop. Store indices so you can fill answer[popped].

Worked examples

three

a = [4, 1, 9]
  1. 1 waits under 4
  2. 9 pops 1 then 4
  3. 9 leftover

Result: [9, 9, none]

four

a = [4, 1, 9, 1]
  1. 9 still pops 1 then 4
  2. last 1 < 9 so it waits
  3. 9 and last 1 leftover

Result: [9, 9, none, none]

singleton

a = [4]
  1. push 0
  2. never popped

Result: [none]

Try it

Write nextGreaterRight(a). a is the list of integers. Return the first later strictly greater value at each index, or none. Pop while a[top] < a[i]. Leftovers get none. [4, 1, 9] → [9, 9, none]. [4, 1, 9, 1] → [9, 9, none, none]. [9, 4, 1] → [none, none, none].

a is a non-empty list of integers.