Why Plain Stacks Hide Two Different Interview Patterns
On the NeetCode roadmap, Stack looks like a single beginner box, yet it splits into two distinct skills in interviews. The first is classic LIFO nesting: bracket validation, reverse Polish evaluation, and decoding nested strings. The second, harder pattern is the monotonic stack, which solves nearest-greater and span-boundary queries that look at first glance.
Whenever a prompt asks for the "next warmer day," "previous smaller bar," or "maximum width rectangle," I stop thinking about nested loops and ask a single question: can an arriving element permanently dominate older waiting elements?
Diagram: Original vector diagram by Ajay Kumar Chaturvedi (CC BY 4.0).
Intuition and Dominance Invariants
1. Monotonic stack: store waiting indices, resolve on pop
Suppose you track temperatures [73, 74, 75, 71, 69, 72, 76] and want how many days each day must wait for a warmer reading.
Keep a stack of indices whose temperatures are monotonically non-increasing from bottom to top. As soon as a hotter temperature arrives at index i, every colder index on top of the stack has found its first warmer future day: i. Pop those indices, compute i - prev_idx, and push i.
I always push indices rather than raw values. From an index idx, you recover both temps[idx] and the distance i - idx without carrying awkward (val, idx) tuples.
Diagram: Original vector diagram by Ajay Kumar Chaturvedi (CC BY 4.0).
For histogram areas, invert the invariant to a monotonic increasing stack of heights. When a shorter bar arrives at index i, the popped height h can no longer extend rightward past i. Its right boundary is i, and its left boundary is the new stack top after popping (-1 if the stack is empty), making the rectangle width i - left_bound - 1. Appending a sentinel height 0 forces every bar on the stack to flush at the end.
Take [2, 1, 5, 6, 2, 3] as a concrete walkthrough. Bar 2 is popped when 1 arrives (width = 1, area 2). Bars 5 and 6 stack upward until bar 2 arrives at i = 4: popping 6 yields width = 4 - 2 - 1 = 1 (area 6), and popping 5 yields width = 4 - 1 - 1 = 2 (area 10). That single monotonic pop reveals why storing indices matters: every popped bar immediately discovers both its left and right strict blockers.
When a prompt moves from a linear array to a circular array (Next Greater Element II), do not copy or concatenate lists explicitly. Simply iterate i across range(2 * n) and index nums[i % n], pushing onto the stack only during the first pass (if i < n:) while letting the second wraparound pass resolve any trailing elements whose next greater neighbor sits near index 0.
2. Monotonic deque: adding a window expiry at the front
What if you no longer want the nearest greater element anywhere in the future, but the maximum inside every sliding window of fixed size ?
As detailed in the CP-Algorithms minimum queue guide, a monotonic deque removes dominated values from the right just like a stack, while also expiring out-of-range indices from the front. Using Python's `collections.deque` keeps both pop() and popleft() in time. For sliding window minimum, keep the deque monotonically increasing (>= pop from back) instead of decreasing (<=).
Working Python Code
Here are all three verified templates: next-warmer-day distances (daily_temperatures), sentinel-flushed histogram area (largest_rectangle_area), and sliding window maximum (sliding_window_max).
from collections import deque
def daily_temperatures(temps: list[int]) -> list[int]:
ans = [0] * len(temps)
stack: list[int] = []
for i, t in enumerate(temps):
while stack and temps[stack[-1]] < t:
prev = stack.pop()
ans[prev] = i - prev
stack.append(i)
return ans
def largest_rectangle_area(heights: list[int]) -> int:
best = 0
stack: list[int] = []
for i, h in enumerate(heights + [0]):
while stack and heights[stack[-1]] > h:
height = heights[stack.pop()]
left = stack[-1] if stack else -1
width = i - left - 1
best = max(best, height * width)
stack.append(i)
return best
def sliding_window_max(nums: list[int], k: int) -> list[int]:
if not nums or k <= 0:
return []
dq: deque[int] = deque()
out: list[int] = []
for i, val in enumerate(nums):
if dq and dq[0] <= i - k:
dq.popleft()
while dq and nums[dq[-1]] <= val:
dq.pop()
dq.append(i)
if i >= k - 1:
out.append(nums[dq[0]])
return out
if __name__ == "__main__":
assert daily_temperatures([73, 74, 75, 71, 69, 72, 76]) == [1, 1, 4, 2, 1, 1, 0]
assert largest_rectangle_area([2, 1, 5, 6, 2, 3]) == 10
assert sliding_window_max([1, 3, -1, -3, 5, 3, 6, 7], 3) == [3, 3, 5, 5, 6, 7]
print("daily_temperatures:", daily_temperatures([73, 74, 75, 71, 69, 72, 76]))
print("largest_rectangle:", largest_rectangle_area([2, 1, 5, 6, 2, 3]))
print("sliding_window_max:", sliding_window_max([1, 3, -1, -3, 5, 3, 6, 7], 3))Executing this script prints:
daily_temperatures: [1, 1, 4, 2, 1, 1, 0]
largest_rectangle: 10
sliding_window_max: [3, 3, 5, 5, 6, 7]Complexity Analysis
| Pattern | Time Complexity | Space Complexity | Key Detail |
|---|---|---|---|
| Monotonic stack (next greater) | Each index enters and leaves stack at most once | ||
| Monotonic stack (histogram) | Sentinel 0 guarantees one final linear flush | ||
Monotonic deque (window max) | Front expiry caps stored candidates at elements |
Notice why the nested while loop never breaks linear bounds. Across an array of items, there are only pushes total, so the total count of pop() calls across the entire loop cannot exceed .
Common Mistakes and When I Skip Monotonic Structures
Four subtle bugs derail monotonic implementations in live interviews:
- Using Python `list.pop(0)` instead of `deque.popleft()`: Calling
pop(0)on a Pythonlistshifts every remaining item in , degrading the sliding window maximum to quietly. - Forgetting the trailing sentinel in histograms: Leaving taller bars stranded on the stack skips the final width calculation up to
len(heights). - Strict vs. non-strict inequality errors: In
daily_temperatures, equal temperatures do not count as warmer (<), whereas insliding_window_max, popping equal older elements (<=) keeps the deque short and fresher. - Wrong left-boundary fallback: After popping the last item from the histogram stack, the left boundary must be
-1so width equalsi - (-1) - 1 == i, not0.
I skip monotonic stacks when the problem needs range-minimum updates over arbitrary dynamic edits (use a segment tree or Fenwick tree), or when window bounds can shrink unpredictably without a fixed or clear dominance relation (a two-heap or balanced multiset fits better when you need the median rather than an extremum).
Practice Problems
Lock in both index-span calculation and dominance invariants with these two problems:
- Daily Temperatures: Practice decreasing stack state and computing wait offsets from stored indices.
- Largest Rectangle in Histogram: Practice increasing stack pops, left/right boundary widths, and sentinel flushing.
