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.