awelgorithms

Next greater to the left

Updated

Next greater to the left of i is the nearest j < i with a[j] > a[i], or none. Scan left to right. Pop while a[top] <= a[i] so remaining tops are strictly greater. Peek that top (do not pop it for the answer). Then push i.

What to focus on

The answer is written from a peek, not from the popped losers. Empty after the while means none to the left. The stack stays decreasing.

Worked examples

three

a = [4, 1, 9]
  1. 4: none
  2. 1: peek 4
  3. 9 pops 1 and 4, none

Result: [none, 4, none]

four

a = [4, 1, 9, 1]
  1. last 1 peeks 9

Result: [none, 4, none, 9]

new max

a = [4, 1, 9], at 9
  1. pops drain
  2. []

Result: none to the left of 9

Try it

Write nextGreaterLeft(a). a is the list of integers. Return the nearest earlier strictly greater value at each index, or none. Peek after pop-while. Then push i. [4, 1, 9] → [none, 4, none]. [4, 1, 9, 1] → [none, 4, none, 9]. [1, 9, 4] → [none, none, 9].

a is a non-empty list of integers.