Skip to content
DSAPrep

    ↑↓ to move · Enter to open · Esc to close

    ← All patterns

    Stack

    Last-in-first-out: match brackets, evaluate expressions, find the next greater element.

    Reach for it when

    • Nested structure: brackets, expressions, path simplification
    • Next / previous greater or smaller element
    • Undo the most recent thing first

    Core idea

    A monotonic stack keeps elements in sorted order; when a new element breaks the order, everything it pops has just found its answer (its next greater or smaller element). Every element is pushed and popped at most once, so the total is O(n).

    Template · O(n) time, O(n) space

    def next_greater(nums):
    ans = [-1] * len(nums)
    stack = [] # indices, values decreasing
    for i, x in enumerate(nums):
    while stack and nums[stack[-1]] < x:
    ans[stack.pop()] = x # x is their next greater
    stack.append(i)
    return ans

    Common pitfalls

    • Store indices, not values, when you need distances or widths
    • Decide strict vs non-strict comparison for equal elements
    • Remember to flush what is left on the stack at the end

    Practice · 0 / 8 done