Stack is a LIFO (Last In, First Out) data structure where elements are added and removed from the same end. It’s perfect for tracking “most recent” state.
def calculate(s): """Evaluate expression with +, -, (, )""" stack = [] result = 0 number = 0 sign = 1 for char in s: if char.isdigit(): number = number * 10 + int(char) elif char == '+': result += sign * number number = 0 sign = 1 elif char == '-': result += sign * number number = 0 sign = -1 elif char == '(': stack.append(result) stack.append(sign) result = 0 sign = 1 elif char == ')': result += sign * number number = 0 result *= stack.pop() # sign result += stack.pop() # previous result return result + sign * number
def daily_temperatures(temperatures): """Days until warmer temperature for each day""" n = len(temperatures) result = [0] * n stack = [] # indices of temperatures waiting for warmer day for i in range(n): while stack and temperatures[i] > temperatures[stack[-1]]: prev_idx = stack.pop() result[prev_idx] = i - prev_idx stack.append(i) return result
def next_greater_element(nums): """For each element, find next greater element or -1""" result = [-1] * len(nums) stack = [] # Stack of indices for i in range(len(nums)): # Pop elements smaller than current while stack and nums[i] > nums[stack[-1]]: idx = stack.pop() result[idx] = nums[i] stack.append(i) return resultdef largest_rectangle_histogram(heights): """Find largest rectangle in histogram""" stack = [] # indices max_area = 0 heights.append(0) # Sentinel for i, h in enumerate(heights): while stack and heights[stack[-1]] > h: height = heights[stack.pop()] width = i if not stack else i - stack[-1] - 1 max_area = max(max_area, height * width) stack.append(i) return max_area
“This is a matching problem, so I’ll use a stack.”
“Opening brackets push, closing brackets pop and compare.”
“If match fails or stack has leftovers, it’s invalid.”
“For monotonic: I maintain a stack where elements are always sorted.”
When Interviewer Says...
Interviewer Says
You Should Think
”Valid parentheses/brackets”
Basic stack push/pop
”Next greater element”
Monotonic decreasing stack
”Largest rectangle”
Monotonic increasing stack
”Evaluate expression”
Two stacks (operand + operator)
“Simplify path”
Stack for directory navigation
Monotonic Stack Template
Copy
def next_greater(arr): result = [-1] * len(arr) stack = [] # stores indices for i in range(len(arr)): # Pop while current is greater than stack top while stack and arr[i] > arr[stack[-1]]: idx = stack.pop() result[idx] = arr[i] stack.append(i) return result