DSA & CS / 3. STACKS & QUEUES
Stacks & Queues
LIFO and FIFO — deceptively powerful patterns
EXPLANATION
Stack (LIFO — Last In First Out): push/pop from the same end. Use Python list as stack (append/pop are O(1)). Queue (FIFO — First In First Out): enqueue at back, dequeue from front. Use collections.deque — O(1) from both ends. Never use list.pop(0) — that's O(n). Monotonic Stack: a stack that maintains elements in sorted order (increasing or decreasing). Used for "next greater element", "largest rectangle", "trapping rain water" problems. When to use stack: • Matching brackets/parentheses → push open, pop on close • Undo operations, browser history • DFS (iterative) • Expression evaluation • Next Greater Element pattern When to use queue: • BFS (level-order traversal) • Sliding window maximum • Task scheduling
DIAGRAM
Stack (LIFO): Queue (FIFO): push(1) → [1] enqueue(1) → [1] push(2) → [1,2] enqueue(2) → [1,2] push(3) → [1,2,3] enqueue(3) → [1,2,3] pop() → 3, [1,2] dequeue() → 1, [2,3] Monotonic Decreasing Stack — Next Greater Element: nums = [2, 1, 2, 4, 3] stack=[] i=0: push 2 → stack=[2] i=1: push 1 → stack=[2,1] i=2: 2>1 pop 1, NGE[1]=2; 2=2 push 2 → stack=[2,2] i=3: 4>2 pop both, NGE[2]=4, NGE[0]=4 → stack=[4] i=4: push 3 → stack=[4,3] result: NGE = [4, 2, 4, -1, -1]
CODE