Stacks and Queues Appear More Often Than You Think
When most people think of LeetCode stack and queue problems, they picture Valid Parentheses and move on. But stacks and queues are quietly behind some of the trickiest and most elegant interview problems — from computing daily temperature spans to finding the largest rectangle in a histogram.
The reason these problems trip people up is not complexity. It is recognition. Once you see that a problem is asking about "the next greater element" or "process items in order," the stack or queue solution becomes almost mechanical. The hard part is knowing when to reach for these structures in the first place.
This guide breaks down the core stack and queue patterns you need for coding interviews: classic bracket matching, the powerful monotonic stack, queue-based traversals, and the mistakes that cost people time on interview day.
Stack Fundamentals — LIFO and When to Reach for a Stack
A stack is a last-in, first-out (LIFO) structure. You push items onto the top and pop them off the top. That single constraint makes stacks surprisingly powerful for a specific class of problems: anything where you need to match, reverse, or track a "most recent" element.
The mental model is simple. Think of a stack of plates. You can only add or remove from the top. In code, this means the most recently added item is always the first one you process — which is exactly what you want when matching opening brackets to closing brackets, or when tracking the nearest larger value.
In interviews, reach for a stack when you see these signals: nested or paired structures (brackets, HTML tags), "nearest" or "next" problems (next greater element, nearest smaller value), expression evaluation, or undo/redo operations. If the problem involves processing things in reverse order of arrival, a stack is almost always the right tool.
- LIFO: last in, first out — the most recently pushed item gets popped first
- O(1) push and pop operations on both arrays and linked lists
- Key signals: matching pairs, "next greater/smaller," expression parsing, backtracking
- In Python use a list as a stack (append/pop); in JavaScript use an array (push/pop)
Parentheses & Bracket Problems — The Classic Stack Pattern
Valid Parentheses (#20) is the gateway stack problem and one of the most frequently asked easy questions in coding interviews. The pattern is straightforward: push each opening bracket onto the stack, and when you encounter a closing bracket, pop the top and check for a match. If the stack is empty at the end, the input is valid.
Min Stack (#155) extends the concept. You need to support push, pop, top, and getMin — all in O(1) time. The trick is maintaining a second stack (or encoding the minimum into each stack entry) so you always know the current minimum without scanning. This problem tests whether you understand that a stack can track auxiliary information alongside its primary data.
These problems are warm-ups, but do not skip them. Interviewers use bracket matching as a filter question, and getting it wrong signals a gap in fundamentals. More importantly, the "push on open, pop on close" pattern reappears in harder problems like parsing arithmetic expressions and validating nested data structures.
- Valid Parentheses (#20): push opening brackets, pop and match on closing brackets — O(n) time, O(n) space
- Min Stack (#155): maintain a parallel min-tracking stack for O(1) getMin
- Generate Parentheses (#22): backtracking with a stack-like count of open vs. closed brackets
- These problems build the intuition for more advanced stack patterns like monotonic stacks
Pro Tip
Monotonic stacks solve 'next greater element' problems in O(n) — recognize the pattern and it clicks
The Monotonic Stack Pattern — Next Greater Element in O(n)
The monotonic stack is one of the most underrated patterns in coding interviews. It solves an entire family of "next greater element" and "next smaller element" problems in linear time — problems that look like they need nested loops at first glance.
The core idea: maintain a stack where elements are always in increasing (or decreasing) order. When a new element arrives, pop everything from the stack that violates the ordering. Each popped element has just found its "next greater" (or "next smaller") value — the new element. Then push the new element. Every item is pushed and popped at most once, so the total work is O(n).
Next Greater Element (#496) is the classic introduction. You iterate through the array, and for each element, you want to know the next value to its right that is strictly larger. Without a monotonic stack, you would use a nested loop — O(n²). With a monotonic stack, you solve it in a single pass.
Daily Temperatures (#739) uses the same pattern but asks "how many days until a warmer temperature?" Instead of storing values, you store indices on the stack. When you pop an index, the distance between the current index and the popped index gives the answer for that day.
Largest Rectangle in Histogram (#84) is the hard-level version. You maintain a monotonic increasing stack of bar heights. When a shorter bar arrives, you pop taller bars and calculate the rectangle each could form. This problem appears in interviews at top tech companies and is a strong differentiator between candidates who know the pattern and those who do not.
- Next Greater Element (#496): single-pass with a decreasing monotonic stack — O(n)
- Daily Temperatures (#739): store indices instead of values, compute distances on pop
- Largest Rectangle in Histogram (#84): monotonic increasing stack, calculate area on pop
- Trapping Rain Water (#42): can be solved with a monotonic stack approach (or two pointers)
- The key insight: if you are writing nested loops to find "the next larger/smaller," try a monotonic stack
Queue Patterns — BFS, Sliding Window Maximum, and Task Scheduling
Queues follow first-in, first-out (FIFO) ordering, and their most important application in coding interviews is breadth-first search. Every BFS traversal — whether on a tree, graph, or matrix — relies on a queue to process nodes level by level. If you have solved Binary Tree Level Order Traversal (#102) or Number of Islands (#200), you have used a queue.
Sliding Window Maximum (#239) is a hard problem that combines queue thinking with the monotonic concept. You maintain a deque (double-ended queue) where elements are in decreasing order. As the window slides, you add new elements to the back (removing smaller elements first) and remove expired elements from the front. The front of the deque always holds the current window maximum. This runs in O(n) instead of the naive O(n * k).
Task Scheduler (#621) is another queue-pattern problem. You need to schedule tasks with a cooldown period between identical tasks. The approach uses a max-heap to pick the most frequent task and a queue to hold tasks in their cooldown period. When a task finishes cooling down, it re-enters the heap. Understanding this interplay between heap and queue is a common interview topic.
The queue pattern is essential whenever order of processing matters. BFS guarantees shortest path in unweighted graphs. Level-order traversal gives you rows of a tree. Task scheduling respects timing constraints. Whenever you need to process items in the order they arrived — or in layers — reach for a queue.
- BFS traversal: queue processes nodes level by level — trees, graphs, matrices
- Sliding Window Maximum (#239): monotonic deque keeps the window max at the front — O(n)
- Task Scheduler (#621): combine a max-heap with a cooldown queue for optimal scheduling
- Rotting Oranges (#994): multi-source BFS using a queue to track the wavefront
Watch Out
Stack problems often look harder than they are — if you're writing nested loops, try a stack instead
Common Mistakes with Stack and Queue Problems
The most frequent mistake with stack problems is using nested loops when a stack gives you a linear solution. If you find yourself writing a loop inside a loop to search for "the next bigger item" or "the nearest smaller item," stop and consider a monotonic stack. The nested-loop approach works but is O(n²), and interviewers expect the O(n) solution.
Another common error is forgetting to pop or to handle the remaining items on the stack after the main loop. In many monotonic stack problems, elements left on the stack at the end have no "next greater element" — you need to handle them explicitly (often by assigning -1 or 0).
With queues, the main pitfall is forgetting the visited set in BFS. Without it, you will revisit nodes and either loop forever or blow up your runtime. Always initialize a visited set before entering the BFS loop, and mark nodes as visited when you enqueue them — not when you dequeue them. Marking on enqueue prevents duplicate entries.
Finally, watch out for off-by-one errors when using deques for sliding window problems. The window boundaries need careful management — elements should be removed from the front of the deque when their index falls outside the window, not just when a new element is added.
- Nested loops for "next greater" problems — use a monotonic stack for O(n) instead of O(n²)
- Forgetting to process remaining stack elements after the main loop
- Missing the visited set in BFS — mark visited on enqueue, not dequeue
- Off-by-one errors in sliding window deque problems — track indices, not just values
Practice Strategy — Building Stack and Queue Intuition
Start with the fundamentals: solve Valid Parentheses (#20) and Implement Stack using Queues (#225) to make sure the basic operations are second nature. These problems should feel trivial before you move on — if they do not, spend more time here.
Next, tackle the monotonic stack trio: Next Greater Element (#496), Daily Temperatures (#739), and Largest Rectangle in Histogram (#84). Solve them in that order. Each builds on the previous one, and by the time you finish the histogram problem, you will have a solid mental model for when monotonic stacks apply.
For queue problems, make sure you are comfortable with BFS on both trees and graphs. Binary Tree Level Order Traversal (#102) and Number of Islands (#200) are essential. Then try Sliding Window Maximum (#239) to see how deques extend the basic queue pattern.
The most effective way to retain these patterns is spaced repetition. Solve a problem today, revisit it in 3 days, then again in a week. YeetCode flashcards are built for exactly this workflow — each card drills the pattern recognition step ("what data structure does this problem need?") so you build the intuition that transfers to new problems on interview day.