Last In, First Out. Like a stack of plates. Powers bracket matching, undo operations, DFS, and monotonic problems.
[][]For each element, find the next element that is greater. O(n) using decreasing monotonic stack.
[][]# Python list as stack — all O(1) stack = [] stack.append(x) # push stack.pop() # pop (crashes if empty!) stack[-1] # peek top not stack # True if empty len(stack) # size # ── Valid Parentheses ── def is_valid(s): stack = [] match = {')':'(', ']':'[', '}':'{'} for c in s: if c in match: if not stack or stack[-1] != match[c]: return False stack.pop() else: stack.append(c) return not stack
if not stack BEFORE stack[-1]. Accessing index on empty list raises IndexError.# Next Greater Element — O(n) def next_greater(arr): res = [-1] * len(arr) stack = [] # stores indices for i, val in enumerate(arr): while stack and arr[stack[-1]] < val: res[stack.pop()] = val stack.append(i) return res # MinStack — O(1) get_min() class MinStack: def __init__(self): self.stack = []; self.min_s = [] def push(self, val): self.stack.append(val) m = val if not self.min_s else min(val, self.min_s[-1]) self.min_s.append(m) def pop(self): self.stack.pop(); self.min_s.pop() def get_min(self): return self.min_s[-1]