Module 2 · Lesson 1 · ~22 min
Stacks and queues are baby-simple data structures. The interview-grade skill is recognizing when a problem secretly is a stack problem — and the monotonic variant that turns O(n²) brute forces into O(n) sweeps.
Stack — a literal stack of plates. You can only put a plate on top, only take a plate from the top. LIFO: last in, first out. The most recent thing you placed is the next thing you'll get back.
Queue — a line at the bakery. You join the back. You're served from the front. FIFO: first in, first out.
Deque ("deck") — a line where people can join or leave at either end. Combines stack and queue powers. The Python collections.deque and the JS Array (used carefully) both support all four operations in O(1).
| Op | Stack | Queue | Deque |
|---|---|---|---|
| Push to back / top | O(1) | O(1) | O(1) |
| Pop from back / top | O(1) | — | O(1) |
| Pop from front | — | O(1) | O(1) |
| Peek | O(1) | O(1) | O(1) at either end |
list.pop(0) is O(n) — it shifts every other element left. Never use a Python list as a queue. Use collections.deque, which gives O(1) at both ends.
A monotonic stack is a stack you maintain with a strict ordering — always increasing, or always decreasing. When a new element would violate the ordering, you pop until it doesn't. Then you push.
The magic: each element is pushed once and popped at most once. Total work over n elements = 2n. Amortized O(n) for problems that look quadratic.
Canonical use case: "next greater element". For each element in the array, find the next element to its right that is strictly greater. Brute force is O(n²). With a decreasing monotonic stack of indices, it's O(n).
def next_greater(nums):
res = [-1] * len(nums)
stack = [] # indices, values strictly decreasing
for i, x in enumerate(nums):
while stack and nums[stack[-1]] < x:
res[stack.pop()] = x
stack.append(i)
return res
# Each index pushed once, popped at most once → O(n) total.
function nextGreater(nums) {
const res = new Array(nums.length).fill(-1);
const stack = []; // indices, values strictly decreasing
for (let i = 0; i < nums.length; i++) {
while (stack.length && nums[stack[stack.length - 1]] < nums[i]) {
res[stack.pop()] = nums[i];
}
stack.push(i);
}
return res;
}
// Each index pushed once, popped at most once → O(n) total.
function nextGreater(nums: number[]): number[] {
const res = new Array(nums.length).fill(-1);
const stack: number[] = []; // indices, values strictly decreasing
for (let i = 0; i < nums.length; i++) {
while (stack.length && nums[stack[stack.length - 1]] < nums[i]) {
res[stack.pop()!] = nums[i];
}
stack.push(i);
}
return res;
}
// Each index pushed once, popped at most once → O(n) total.
"The inner while looks like it makes this O(n²), but each element is pushed exactly once and popped at most once across the entire run. Total work is 2n, so amortized O(n)." Say that sentence. It's gold.
The same idea applied to a sliding window. To get the max of every length-k window in O(n), maintain a deque of indices whose values form a decreasing sequence. The front is always the index of the current window's max.
from collections import deque
def window_max(nums, k):
dq = deque() # indices, values decreasing
out = []
for i, x in enumerate(nums):
while dq and nums[dq[-1]] < x:
dq.pop()
dq.append(i)
if dq[0] == i - k:
dq.popleft()
if i >= k - 1:
out.append(nums[dq[0]])
return out
function windowMax(nums, k) {
const dq = []; // indices, values decreasing
const out = [];
for (let i = 0; i < nums.length; i++) {
while (dq.length && nums[dq[dq.length - 1]] < nums[i]) dq.pop();
dq.push(i);
if (dq[0] === i - k) dq.shift();
if (i >= k - 1) out.push(nums[dq[0]]);
}
return out;
}
function windowMax(nums: number[], k: number): number[] {
const dq: number[] = []; // indices, values decreasing
const out: number[] = [];
for (let i = 0; i < nums.length; i++) {
while (dq.length && nums[dq[dq.length - 1]] < nums[i]) dq.pop();
dq.push(i);
if (dq[0] === i - k) dq.shift();
if (i >= k - 1) out.push(nums[dq[0]]);
}
return out;
}