Module 2 · Drill 1 · stack reps

Stack & queue drills

Four classics. The first two are warmup; the last two need monotonic-stack thinking. Each gets you another rep at saying "amortized O(n) — each element pushed and popped at most once."

1 — Daily temperatures

For each day's temperature, return the number of days you'd have to wait until a warmer one. 0 if no warmer day exists. Monotonic decreasing stack of indices.

2 — Implement a queue using two stacks

Use only stack operations (push to top, pop from top, peek top). Implement a class with O(1) amortized enqueue and dequeue.

3 — Largest rectangle in histogram (monotonic stack)

Bars of varying heights. Find the largest rectangle that fits entirely under the bars. Monotonic increasing stack of indices.

4 — Sliding window max (monotonic deque)

Solutions

1 — Daily temperatures

def daily_temps(temps):
    out = [0] * len(temps)
    stack = []   # indices, values strictly decreasing
    for i, t in enumerate(temps):
        while stack and temps[stack[-1]] < t:
            j = stack.pop()
            out[j] = i - j
        stack.append(i)
    return out
  
function dailyTemps(temps) {
  const out = new Array(temps.length).fill(0);
  const stack = [];
  for (let i = 0; i < temps.length; i++) {
    while (stack.length && temps[stack[stack.length - 1]] < temps[i]) {
      const j = stack.pop();
      out[j] = i - j;
    }
    stack.push(i);
  }
  return out;
}
  
function dailyTemps(temps: number[]): number[] {
  const out: number[] = new Array(temps.length).fill(0);
  const stack: number[] = [];
  for (let i = 0; i < temps.length; i++) {
    while (stack.length && temps[stack[stack.length - 1]] < temps[i]) {
      const j = stack.pop()!;
      out[j] = i - j;
    }
    stack.push(i);
  }
  return out;
}
  
Amortized O(n). Each index pushed and popped at most once. Monotonic decreasing stack of indices — when a warmer day comes, every pending index pops and records its wait time.

2 — Queue from two stacks

class MyQueue:
    def __init__(self):
        self.inn = []
        self.out = []
    def enqueue(self, x):
        self.inn.append(x)
    def dequeue(self):
        if not self.out:
            while self.inn:
                self.out.append(self.inn.pop())
        return self.out.pop() if self.out else None

def run(ops_and_args):
    q = MyQueue()
    out = []
    for op in ops_and_args:
        if op[0] == 'enqueue': q.enqueue(op[1])
        elif op[0] == 'dequeue': out.append(q.dequeue())
    return out
  
class MyQueue {
  constructor() { this.in = []; this.out = []; }
  enqueue(x) { this.in.push(x); }
  dequeue() {
    if (!this.out.length) {
      while (this.in.length) this.out.push(this.in.pop());
    }
    return this.out.pop();
  }
}
function run(ops) {
  const q = new MyQueue();
  const out = [];
  for (const op of ops) {
    if (op[0] === 'enqueue') q.enqueue(op[1]);
    else if (op[0] === 'dequeue') out.push(q.dequeue());
  }
  return out;
}
  
class MyQueue<T> {
  private inn: T[] = [];
  private out: T[] = [];
  enqueue(x: T): void { this.inn.push(x); }
  dequeue(): T | undefined {
    if (!this.out.length) {
      while (this.inn.length) this.out.push(this.inn.pop()!);
    }
    return this.out.pop();
  }
}
function run(ops: any[]): any[] {
  const q = new MyQueue<any>();
  const out: any[] = [];
  for (const op of ops) {
    if (op[0] === 'enqueue') q.enqueue(op[1]);
    else if (op[0] === 'dequeue') out.push(q.dequeue());
  }
  return out;
}
  
Amortized O(1) per op. Each element moves between the two stacks at most twice (in → out). The drain-when-empty trick is the key — moving lazily means each dequeue isn't paying for the move every time.

3 — Largest rectangle in histogram

def largest_rect(heights):
    stack = []      # indices with strictly increasing heights
    best = 0
    # append a sentinel 0 to flush the stack at the end
    for i, h in enumerate(heights + [0]):
        while stack and heights[stack[-1]] > h:
            top = stack.pop()
            left = stack[-1] if stack else -1
            width = i - left - 1
            best = max(best, heights[top] * width)
        stack.append(i)
    return best
  
function largestRect(heights) {
  const stack = [];
  let best = 0;
  const arr = [...heights, 0];
  for (let i = 0; i < arr.length; i++) {
    while (stack.length && arr[stack[stack.length - 1]] > arr[i]) {
      const top = stack.pop();
      const left = stack.length ? stack[stack.length - 1] : -1;
      const width = i - left - 1;
      best = Math.max(best, arr[top] * width);
    }
    stack.push(i);
  }
  return best;
}
  
function largestRect(heights: number[]): number {
  const stack: number[] = [];
  let best = 0;
  const arr = [...heights, 0];
  for (let i = 0; i < arr.length; i++) {
    while (stack.length && arr[stack[stack.length - 1]] > arr[i]) {
      const top = stack.pop()!;
      const left = stack.length ? stack[stack.length - 1] : -1;
      const width = i - left - 1;
      best = Math.max(best, arr[top] * width);
    }
    stack.push(i);
  }
  return best;
}
  
Amortized O(n). Increasing-monotonic stack. When a bar shorter than the top arrives, the top is "closed off" — its rectangle stretches from one past the new top of the stack (or 0 if empty) to just before the current index. The trailing sentinel 0 forces the stack to drain at the end.

4 — Sliding window max (monotonic deque)

from collections import deque

def window_max(nums, k):
    dq = deque()    # indices, values decreasing
    out = []
    for i, x in enumerate(nums):
        while dq and dq[0] <= i - k:
            dq.popleft()
        while dq and nums[dq[-1]] < x:
            dq.pop()
        dq.append(i)
        if i >= k - 1:
            out.append(nums[dq[0]])
    return out
  
function windowMax(nums, k) {
  const dq = [];
  const out = [];
  for (let i = 0; i < nums.length; i++) {
    while (dq.length && dq[0] <= i - k) dq.shift();
    while (dq.length && nums[dq[dq.length - 1]] < nums[i]) dq.pop();
    dq.push(i);
    if (i >= k - 1) out.push(nums[dq[0]]);
  }
  return out;
}
  
function windowMax(nums: number[], k: number): number[] {
  const dq: number[] = [];
  const out: number[] = [];
  for (let i = 0; i < nums.length; i++) {
    while (dq.length && dq[0] <= i - k) dq.shift();
    while (dq.length && nums[dq[dq.length - 1]] < nums[i]) dq.pop();
    dq.push(i);
    if (i >= k - 1) out.push(nums[dq[0]]);
  }
  return out;
}
  
O(n) — each index pushed and popped once. The deque holds indices whose values form a decreasing sequence; the front is always the max of the current window.