Stack & Monotonic Stack
When to use: matching/nesting (parentheses, decode), expression evaluation, "undo" behaviour, and next greater / smaller element questions.
Monotonic stack: keep indices whose values are increasing (or decreasing). When a new value breaks the order, pop — the popped index has just found its next greater/smaller element. Each index is pushed and popped once → O(n).
# next greater element to the right, for every index
res, st = [-1] * n, [] # st holds indices with decreasing values
for i, x in enumerate(a):
while st and a[st[-1]] < x:
res[st.pop()] = x
st.append(i)
Problems
Showing 24 of 24