awelgorithms

Next smaller to the right

Updated

Next smaller of i is the first j > i with a[j] < a[i], or none. Scan left to right with an increasing index stack. Pop while a[top] > a[i]; those popped indices just found i. Then push i. Leftovers have none.

What to focus on

Flip only the test versus next-greater. Equal values: strictly smaller means == does not pop.

Worked examples

three

a = [4, 1, 9]
  1. 1 pops 4 (next smaller of 4 is 1)
  2. 9 > 1, no pop
  3. 1 and 9 leftover

Result: [1, none, none]

four

a = [4, 1, 9, 1]
  1. last 1 pops 9
  2. earlier 1 is not > last 1

Result: [1, none, 1, none]

singleton

a = [4]
  1. never popped

Result: [none]

Try it

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

a is a non-empty list of integers.