awelgorithms

Next smaller to the left

Updated

Next smaller 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 smaller. Peek, then push i. Empty peek is none.

What to focus on

This is the histogram left bound. The stack stays increasing. Do not walk left from i by hand.

Worked examples

three

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

Result: [none, none, 1]

four

a = [4, 1, 9, 1]
  1. last 1 pops 9 then the equal 1
  2. []

Result: [none, none, 1, none]

peek kept

a = [4, 1, 9], at 9
  1. 1 < 9
  2. leave 1
  3. push 2

Result: previous smaller 1

Try it

Write nextSmallerLeft(a). a is the list of integers. Return the nearest earlier strictly smaller value at each index, or none. Peek a leftover top that is strictly smaller, then push i. [4, 1, 9] → [none, none, 1]. [4, 1, 9, 1] → [none, none, 1, none]. At 9 on [4, 1, 9] the previous smaller is 1.

a is a non-empty list of integers.