progress

~/problems / Stacks / Monotonic stack

Nearest smaller value to the left

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy basics ~10 min

Write prev_smaller(nums: list[int]) -> list[int]: for each index i, the closest index j < i with nums[j] < nums[i] (strictly), or -1 if none.

prev_smaller([3, 1, 4, 1, 5])   # [-1, -1, 1, -1, 3]
#  3: nothing before it          -> -1
#  1: 3 is not smaller           -> -1
#  4: nums[1] = 1 is smaller     ->  1
#  1: equal is not smaller       -> -1
#  5: nums[3] = 1 is the closest ->  3

prev_smaller([2, 5, 7])         # [-1, 0, 1]

Up to 2 * 10^5 values. ⭐ Bonus: a speed test earns a star in O(n).

Show hint

keep a stack of indexes with increasing values. For each new value, pop everything >= it; the top (if any) is the answer. Then push.

Topic: Monotonic stack. Next greater/smaller element in O(n); histogram rectangles; trapping water.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc