Next Smaller Element
For each element, find the first smaller element to its right (−1 if none).
Open on GeeksforGeeks ↗Intuition
Next Greater with the comparison flipped: keep an increasing stack of waiters; each new element pops — answers — every waiter larger than it.
Identical machinery to next-greater with the comparison flipped, which also flips what the stack holds: values now sit in increasing order. Seeing that one operator controls the stack's whole invariant is the transferable part — it's how you'd derive previous-smaller or previous-greater on the spot.
Approach
Mirror the monotonic stack
Stack holds indices with increasing values. New value x pops all waiters > x; x is their next smaller.
Drain leftovers as −1
Anything still waiting at the end has no smaller element to its right.
Same amortized bound
Push+pop once per index → O(n).
Solution & live demo
Common pitfalls
Flipping the comparison but expecting a decreasing stack
stack = [] # indices, values decreasing while stack and nums[stack[-1]] > x:
stack = [] # indices, values increasing while stack and nums[stack[-1]] > x:
The code is right; the mental model isn't. Popping everything larger than the newcomer leaves the stack increasing from bottom to top. Carrying over next-greater's "decreasing" assumption is what makes the follow-up variants go wrong.
Using >= and mis-answering equal values
while stack and nums[stack[-1]] >= x:
while stack and nums[stack[-1]] > x:
An equal element is not smaller, so resolving a pending index with it reports a wrong answer — on [2, 2] the first index would get 2 instead of -1. Strictness in the pop test must match strictness in the question.
Edge cases
No pops until the end — all −1? No: each element's right neighbours are larger, so yes, all −1.
Strictly-smaller wanted → equals stay on the stack.