Stacks & Queues — Complete Guide: All Patterns & Problem Index
Master every stack and queue pattern: monotonic stack, BFS, two-stack tricks, deque, and design — with templates and full index of 50 problems.
webcoderspeed.com
50 articles
Master every stack and queue pattern: monotonic stack, BFS, two-stack tricks, deque, and design — with templates and full index of 50 problems.
Check if a string of brackets is valid by pushing open brackets and matching close brackets against the stack.
Implement a stack using one queue by rotating all elements after each push to bring the new element to the front.
Implement a queue using two stacks with amortized O(1) operations by lazily transferring from inbox to outbox.
Design a stack with O(1) getMin by maintaining a parallel min-tracking stack alongside the main stack.
Simulate a baseball scoring game using a stack to track valid scores and handle +, D, and C operations.
Compare two strings after applying backspace characters in O(1) space by scanning from right with skip counters.
Track the minimum number of operations to return to the main folder by simulating directory navigation with a depth counter.
Count ping requests within the last 3000ms using a queue that slides expired entries off the front.
Remove adjacent pairs of same letters with different cases using a stack to build the result character by character.
Find how many days until a warmer temperature using a monotonic decreasing stack of unresolved day indices.
Find the next greater element for each query in O(n+m) using a monotonic stack on nums2 and a lookup map.
Find the next greater element in a circular array by iterating twice (0 to 2n) and using a monotonic stack.
Calculate the stock price span (consecutive days <= today) using a monotonic stack that accumulates spans.
Remove k digits to form the smallest number by maintaining a monotonic increasing stack and greedy removal.
Decode a string with nested encodings like 3[a2[bc]] using two stacks: one for counts and one for partial strings.
Evaluate an RPN expression by pushing numbers and applying operators to the top two stack elements.
Find the maximum in each sliding window of size k using a monotonic decreasing deque storing indices.
Simulate asteroid collisions using a stack where right-moving asteroids wait and left-moving ones destroy smaller ones.
Sum the minimums of all subarrays by computing each element's contribution as the minimum using previous and next smaller element spans.
Calculate the score of balanced parentheses where () = 1 and AB = A+B and (A) = 2*A using a stack depth trick.
Find the minimum intervals to execute all tasks with cooldown n by greedily scheduling the most frequent task first.
Find minutes until all oranges rot using multi-source BFS starting from all initially rotten oranges simultaneously.
Count islands in a 2D grid using BFS or DFS to flood-fill connected land cells, marking them visited.
Detect if all courses can be finished (no cycle) using Kahn's algorithm: BFS on in-degree zero nodes.
Return a valid course order using Kahn's BFS topological sort, or empty array if a cycle exists.
Find the shortest word transformation sequence using BFS where each step changes exactly one character.
Evaluate a string expression with +, -, *, / using a stack that handles operator precedence without parentheses.
Detect a 132 pattern (i < j < k, nums[i] < nums[k] < nums[j]) using a monotonic stack scanning right to left.
Count visible people in a queue for each person using a monotonic decreasing stack scanning right to left.
Implement a circular queue using a fixed-size array with head and tail pointers and a size counter.
Find cells that can flow to both oceans by doing reverse BFS from each ocean's borders and finding the intersection.
Maximize score jumping through an array with window k by combining DP with a monotonic decreasing deque.
Find the shortest subarray with sum >= k using a monotonic deque on prefix sums for O(n) time.
Fill each empty room with its distance to nearest gate using simultaneous multi-source BFS from all gates.
Implement an iterator for a nested list using a stack that lazily expands nested lists as elements are consumed.
Remove k adjacent identical characters repeatedly using a stack that tracks (character, count) pairs.
Design a hit counter that returns hits in the past 5 minutes using a queue to expire old timestamps.
Find the largest rectangle in a histogram by computing left and right boundaries using a monotonic increasing stack.
Find the maximal rectangle in a binary matrix by building histogram heights row by row and applying largest rectangle.
Evaluate a basic expression with +, -, and parentheses using a stack to save and restore sign context.
Design a frequency stack with O(1) push and pop-max-frequency using a map of frequency to stack of elements.
Find the median dynamically as numbers are added using two heaps: a max-heap for the lower half and min-heap for upper.
Serialize a binary tree to a string using BFS level-order and deserialize back using a queue for reconstruction.
Calculate trapped rainwater volume using a monotonic stack that computes water in horizontal layers as bars are processed.
Complete cheatsheet for Stacks & Queues: all 7 patterns, template code, Big O reference, and MAANG interview priority guide.
Build scalable AI background processing with BullMQ, idempotent job tracking, exponential backoff, progress streaming, and webhook callbacks for reliable async workflows.
Design a hit counter that counts hits in the last 5 minutes using a deque-based sliding window or circular buffer with O(1) amortised operations.
Design a phone directory managing available and allocated numbers with O(1) get, check, and release using a queue of free numbers and a boolean availability array.
Implement a circular queue (ring buffer) with fixed capacity supporting enQueue, deQueue, Front, Rear, isEmpty, and isFull in O(1) time using head and tail pointers.