Software interviews
Stacks and queues for coding interviews: how they work and problems by level
Stacks and queues appear across nearly every software engineering interview level, both as standalone prompts and as tools for graph searches, tree traversals, and sliding windows. Once you grasp their ordering rules, operation costs, and core patterns, you can tackle unfamiliar variations under time pressure instead of memorizing scripts.
Your first hour with George Li (60 minutes by video, $250) ends with a written plan within one working day.
Book your first hour ($250)Five representative stack and queue interview prompts
Start by looking at five classic prompts that show how stacks and queues appear in technical screens and onsite coding rounds:
- Bracket validation: Given a string of round parentheses, curly braces, and square brackets, check whether every opening symbol closes in valid nested order.
- Minimum qualifying subarray: Given an integer array and a threshold k, find the shortest non-empty contiguous slice whose sum reaches or exceeds k.
- Postfix expression math: Evaluate an arithmetic formula written in Reverse Polish Notation, where each operator follows its operands.
- Max-tracking stack: Implement a stack supporting standard push and pop actions while returning the maximum stored value.
- Fixed-capacity circular queue: Design a ring-buffer queue that reuses freed front slots after earlier items leave.
These five prompts span matching, monotonic deques, expression parsing, auxiliary tracking, and modular indexing. Mastering the fundamentals underneath makes each variation clear.
How stacks and queues work under the hood
Both data structures store ordered sequences meant for single-element endpoint access rather than arbitrary random reads.
LIFO versus FIFO ordering and core operations
A stack uses Last In, First Out (LIFO) ordering. Think of stacked plates or chairs: whatever sits highest on the pile comes off first. A queue uses First In, First Out (FIFO) ordering, just like a waiting line where the earliest arrival gets served first.
Each structure revolves around inserting an element, removing the next logical element, and inspecting the upcoming item:
- Push: Places a new element onto a stack’s top position.
- Pop: Removes and returns the stack’s most recently inserted item.
- Enqueue: Appends a new element at the rear of a queue.
- Dequeue: Removes and returns the queue’s oldest item from the front.
- Peek: Reads the next item pop or dequeue would return without modifying the collection.
Capacity bounds, overflow, and underflow
In theory, stacks and queues have unbounded capacity. In practice, hardware memory and fixed-buffer implementations enforce limits. Inserting into a full structure triggers a stack overflow or queue overflow error. Removing from an empty structure causes a stack underflow or queue underflow error. Always check emptiness before calling pop, dequeue, or peek.
Built-in types in Java, C++, and Python
Knowing your interview language’s standard containers avoids wasted setup time:
- Java: Ships a legacy Stack class extending Vector, though interviewers usually prefer Deque implementations like ArrayDeque for faster single-threaded performance.
- C++: The STL offers containers with push and pop methods, plus stack and queue adapters wrapping a vector, deque, or list for strict LIFO or FIFO access.
- Python: Includes collections.deque, a double-ended queue supporting fast front and back operations so one class serves as either a queue or a stack (alongside lists for stacks).
Array, linked list, and deque implementations
Their abstract interface, not a single storage layout, defines how stacks and queues behave. Most implementations use arrays or linked lists, and interviewers often ask how both compare.
An array-backed stack tracks the index of its highest occupied slot. Pushing writes at the next free slot and increments that index; popping reads the current slot and decrements it. Array-backed queues rely on circular wraparound indices so front removals avoid O(n) shifts.
A linked-list implementation tracks both head and tail pointers for constant-time endpoint updates. A stack pushes and pops at one end, while a queue enqueues at the tail and dequeues at the head. A deque (double-ended queue) supports insertion and removal at both ends in O(1) time, letting it act as either structure.
Cheat sheet: operation complexities and related patterns
Memorizing Big-O values without knowing why they hold fails under follow-up probing. Use this table as a summary and explain each bound from the pointer or index mechanics.
| Operation | Stack | Queue | Deque | Underlying reason |
|---|---|---|---|---|
| Push / Enqueue | O(1) | O(1) | O(1) | Writes directly at top, tail, or either endpoint |
| Pop / Dequeue | O(1) | O(1) | O(1) | Removes from top, head, or either end without shifting |
| Peek / Front | O(1) | O(1) | O(1) | Reads the tracked endpoint reference directly |
| Search by value | O(n) | O(n) | O(n) | Needs a linear scan; rarely exposed by strict APIs |
| Memory space | O(n) | O(n) | O(n) | Holds one slot or node per stored element |
Core stack and queue operations take constant time because linked lists and indexed arrays add or remove endpoints directly. Searching for a specific element generally requires linear time across the underlying storage, which is why standard interfaces rarely provide a search method.
Connected algorithms and techniques
Stacks and queues frequently power broader algorithmic techniques:
- Monotonic stack: Keeps items sorted monotonically to resolve next greater or smaller elements in linear time.
- Monotonic queue: Tracks candidate extrema in a deque for O(1) amortized sliding-window queries.
- Circular queue: Wraps array indices with modulo arithmetic for fixed-buffer designs.
- Sliding window: Combines a queue or deque with window boundaries over contiguous subarrays.
- Recursion and backtracking: Run on an implicit call stack that an explicit stack can replace iteratively.
- Dynamic programming and greedy algorithms: Often use monotonic stacks or deques to speed up transitions.
How to practice coding questions without memorizing answers
Reading and memorizing every online prompt is impossible because interviewers write fresh variations. Use practice problems to build pattern recognition and problem-solving habits.
- Simulate interview pressure: Set a strict timer and solve each prompt without hints, syntax lookups, or notes.
- Match format to interview stage: Talk through easy prompts without an IDE for phone screens, and write full code or whiteboard sketches for video and onsite rounds.
- Check solutions only after stalling: If you get stuck after serious effort, study one clean solution, then close it and solve the next prompt solo.
- Skip passive reading loops: Reading dozens of answers back-to-back builds familiarity without recall.
10 easy stack and queue interview questions
Easy prompts frequently appear in phone screens, where you may need to reason aloud without running code or drawing on a whiteboard.
- Balanced brackets check: Verify whether every opening bracket matches a closing bracket in proper last-opened, first-closed order.
- Minimum-tracking stack: Support push, pop, top lookup, and retrieving the smallest stored value in O(1) time.
- Stack via queues: Simulate LIFO push and pop using only FIFO queue operations.
- Queue via two stacks: Build FIFO enqueue and dequeue behavior using an input stack and an output stack.
- Next greater value (subset): For items in one array, locate their positions in a second array and find the first larger value to the right.
- Backspace string comparison: Check whether two strings match after applying hash characters that delete the prior letter.
- Adjacent duplicate removal: Repeatedly cancel neighboring identical characters in a string until none remain.
- Array reconstruction with stack ops: Output push and pop commands that turn integers 1 through n into a target sequence.
- Discounted shop prices: Subtract from each item price the first later price that is less than or equal to it.
- Recent call counter: Log request timestamps and report how many calls happened within the past 3,000 milliseconds.
27 medium stack and queue interview questions
Medium prompts anchor most video and onsite interviews. Be ready to write bug-free code, trace edge cases, and analyze complexity.
Expression parsing, nesting, and string cleanup
- Path canonicalization: Simplify a Unix directory path containing extra slashes, single dots, and parent-directory jumps.
- Reverse Polish Notation evaluator: Scan tokens left to right, popping two operands at each operator and pushing the computed result.
- Arithmetic calculator without parentheses: Evaluate integers with addition, subtraction, multiplication, and division following operator precedence.
- Smallest unique-letter string: Delete duplicate characters so each distinct letter appears once in minimal alphabetical order.
- Nested integer list iterator: Flatten arbitrarily nested integer lists lazily using an explicit stack.
- Encoded repeat string decoder: Expand bracketed patterns preceded by repeat counts, including nested brackets.
- Smallest number after k deletions: Remove k digits from a numeric string to produce the minimum integer.
- Forward-ordered linked list addition: Sum two numbers stored most-significant-digit first in linked lists using stacks.
- Valid bracket generation: Enumerate all well-formed strings of n matched parenthesis pairs via recursive call-stack tracking.
- Parenthesis nesting score: Score balanced parentheses where empty pairs equal 1, adjacent pairs sum, and nested pairs double.
- Smallest distinct-character subsequence: Return the earliest alphabetical subsequence containing every unique letter in the string once.
- Reverse substrings inside parentheses: Flip text inside each bracket pair from innermost outward and drop the brackets.
- Remove k-length adjacent duplicates: Repeatedly strip contiguous runs of k matching letters using character-count pairs on a stack.
Monotonic stacks, simulations, and custom queues
- 132 pattern check: Detect indices i < j < k with nums[i] < nums[k] < nums[j] using a monotonic stack.
- Circular next greater element: Find the first strictly larger number after each element while wrapping around the array.
- Exclusive function time profiler: Compute each function’s net CPU runtime from single-threaded start and end timestamps.
- Asteroid collision simulation: Resolve head-on collisions between left-moving and right-moving objects by comparing sizes.
- Days until warmer weather: Count how many days each temperature reading waits for a strictly higher temperature.
- Online stock span: Report consecutive prior days with prices at or below each incoming daily stock quote.
- Sum of subarray minimums: Sum every contiguous slice’s minimum by tracking how far left and right each value dominates.
- Validate push and pop sequences: Check whether a given pop order can emerge from a push sequence.
- Maximum width ramp: Maximize j - i with i < j and nums[i] <= nums[j] via a decreasing candidate stack.
- Next larger linked list node: Find the first strictly greater node value following each node in a singly linked list.
- Minimum-cost tree from leaf values: Merge adjacent numbers greedily with a monotonic stack to minimize non-leaf product sums.
- Circular queue design: Implement a fixed-size ring buffer supporting enqueue, dequeue, front, rear, empty, and full operations.
- Reveal cards in sorted order: Order a deck so dealing the top card and rotating the next card to the bottom outputs increasing values.
- Front-middle-back queue: Support O(1) insertions and deletions at all three positions using two balanced deques.
13 hard stack and queue interview questions
Hard prompts appear less frequently, usually in onsite loops with extra time for tricky invariants and optimizations.
- Longest valid bracket substring: Find the longest contiguous well-formed slice inside an unbalanced parenthesis string.
- Trapping rainwater: Compute total water retained between elevation bars using a monotonic stack or two pointers.
- Largest histogram rectangle: Find the largest rectangular area under bar heights using a non-decreasing index stack.
- Maximal binary-grid rectangle: Accumulate column heights per row and reuse histogram-stack logic to find the biggest all-ones rectangle.
- Full calculator with parentheses: Evaluate expressions combining integers, plus and minus operators, unary negation, spaces, and nested parentheses.
- Maximum frequency stack: Pop whichever item holds the highest occurrence count, breaking ties by most recent push.
- Odd-even array jumps: Count starting indices reaching the array end by alternating smallest-larger and largest-smaller jumps.
- Constrained subsequence sum: Maximize a subsequence sum with adjacent index gaps capped at k using DP and a monotonic deque.
- Sliding window maximum: Return each k-width window’s peak value in O(n) total time via a decreasing deque.
- Most competitive k-length subsequence: Select the lexicographically smallest subsequence of length k from an integer array.
- Visible people in line: Count how many people ahead each person can see before a taller person blocks the view.
- Shortest subarray reaching sum k: Combine prefix sums with an increasing deque to handle negative numbers and find the minimum-length slice.
- Reverse-stamping a sequence: Work backward using a queue of matching windows to recover valid overlapping stamp placements.
Four practice problems, in order of difficulty
These are our own practice problems, written for this site. Try each on paper first, then open the working. The set runs from matching brackets to the maximum of every window.
Problem 1. The string is (()))(()()))((. What is the fewest characters you must delete so that the string of parentheses that remains is balanced, meaning every ( is closed by a later ) and every ) closes an earlier (? Give an integer.
Show the answer and the working
Answer: 4
- Scan left to right with a counter that plays the part of a stack holding only open brackets. An ( adds one. A ) removes one if the counter is above 0, and otherwise it cannot be matched and is counted as a delete.
- In positions 1 to 14 the counter goes 1, 2, 1, 0, then the ) at position 5 finds 0 and is counted (1 delete). The counter then goes 1, 2, 1, 2, 1, 0, and the ) at position 12 finds 0 and is counted (2 deletes). The last two characters are ( and ( and raise the counter to 2.
- The 2 open brackets still on the stack at the end can never be closed, so they are deleted too.
- The total is 2 + 2 = 4. One pass, O(n) time and O(1) space because only a count is needed.
Problem 2. The values are 6, 2, 9, 4, 5, 8, 3, 7, 1, 10, 4, in order. For each position, find the distance to the next position on its right that holds a strictly larger value, and use 0 if there is none. What is the sum of the eleven distances? Give an integer.
Show the answer and the working
Answer: 20
- Keep a stack of positions whose next larger value has not been found. Their values never increase from the bottom to the top. When a new value is larger than the value at the top, pop that position and record the distance from it to the new position.
- With 0-based positions: 6 and 2 are pushed. The 9 at position 2 pops position 1 (distance 1) and position 0 (distance 2), then is pushed. The 4 is pushed, and the 5 at position 4 pops position 3 (distance 1) and is pushed.
- The 8 at position 5 pops position 4 (distance 1) and stops at the 9, then is pushed. The 3 is pushed, and the 7 at position 7 pops position 6 (distance 1) and stops at the 8. The 1 is pushed.
- The 10 at position 9 pops position 8 (distance 1), position 7 (distance 2), position 5 (distance 4) and position 2 (distance 7). The 10 and the last 4 are never popped, so they count 0.
- The distances in position order are 2, 1, 7, 1, 1, 4, 1, 2, 1, 0, 0, and they sum to 20. Each position is pushed once and popped at most once, so the total work is O(n).
Problem 3. Ten people numbered 1 to 10 stand in a circle in order. Starting at person 1 and counting, every third person still in the circle leaves, and counting resumes with the next person. Who is the last person left? Give an integer.
Show the answer and the working
Answer: 4
- Hold the people in a queue. To remove every third, move the first two people from the front to the back, then remove the person now at the front. Repeat until one person remains.
- The people leave in the order 3, 6, 9, 2, 7, 1, 8, 5, 10.
- Nine people have left, so the last person is the one never removed: 4.
- Each move or removal is O(1) with a queue built for it, so the whole simulation takes O(nk), here 10 x 3 moves. A list used as the queue would make each front removal O(n).
Problem 4. The values are 1, 3, -1, -3, 5, 3, 6, 7, 2, 9, 4. Every window of 4 consecutive values is taken, and the largest value in each window is noted. What is the sum of those maximums over all windows? Give an integer.
Show the answer and the working
Answer: 51
- Keep a deque of positions inside the current window whose values decrease from front to back. A new value first removes any smaller values from the back, since they can never be a maximum while the new value is in the window. The front is the maximum, and it is removed when it slides out of the window.
- There are 11 - 4 + 1 = 8 windows. Their maximums are 3, 5, 5, 6, 7, 7, 9 and 9.
- The sum is 3 + 5 + 5 + 6 + 7 + 7 + 9 + 9 = 51.
- Each position enters and leaves the deque once, so the whole pass is O(n), against O(nk) for finding each maximum from scratch.
Every answer above is recomputed by a separate program when the site is built, and each is rebuilt by a different route from the written steps. A wrong answer would stop the build. Read how the problems are checked.
These are our own practice problems, written for this site. If you have signed an agreement about an assessment, keep its contents to yourself, including in a coaching session.
A longer ladder of stacks and queues problems
Four worked problems are a start, and a longer list is worth having for the weeks before an interview. The table sorts 24 problem types that interviewers often use for stacks and queues into three sets, with what each set trains. A coaching company that publishes a large question list on this topic sorts its own list by the stage where such questions tend to turn up: simpler ones on a phone screen, harder ones on a video call or onsite round, where you may get more time. We keep that idea and describe each type in our own words.
| Set | Types | Problems to look up | What the set trains |
|---|---|---|---|
| Easy | 7 | matching brackets; a stack that reports its minimum; a stack built from queues and the reverse; the next larger element; comparing strings with backspaces; removing adjacent duplicates; counting recent requests | Last in, first out and first in, first out on short inputs |
| Medium | 10 | simplifying a file path; evaluating reverse Polish notation; a basic calculator; decoding a nested string; removing k digits to make the smallest number; daily temperatures; asteroid collisions; an online stock span; a circular queue; checking whether a stack order is possible | A monotonic stack: keep a stack in order and pop what no longer matters |
| Hard | 7 | the longest valid bracket string; trapped rain water; the largest rectangle under a histogram; a calculator with brackets; a stack that pops the most frequent item; the maximum of every window; the shortest stretch whose sum reaches a target | A monotonic stack or deque combined with a window or a design requirement |
Do not try to read every solution. New questions appear every season, so the aim is to own the pattern behind a set, not the answer to each item. For each problem, set a timer, write your own attempt with no reference, and only then read a solution. When you get stuck, look at one solution, close it and redo the problem from a blank page the next day. A pile of read solutions teaches far less than a few redone from memory.
The pattern worth owning is the monotonic stack, where each new value pops every entry it makes useless. Problems that ask for the next larger value, a span or a rectangle under a bar chart all use it, and each item is pushed and popped once, so the cost is linear.
Round out your prep with companion structures and live mocks
Strong interview performance pairs stack and queue fluency with the other core data structures tested in coding loops:
- Arrays and strings: Essential for sliding windows, two-pointer scans, and token parsing.
- Linked lists: Core to pointer mechanics and constant-time queue internals.
- Trees and graphs: Depend on stacks for depth-first search and queues for breadth-first traversal.
- Hash maps and heaps: Commonly paired with stacks or queues for frequency counts and priority scheduling.
Once those fundamentals click, transition to timed mock sessions. Explaining your logic aloud while coding feels unnatural at first, yet vocalizing invariants, complexity tradeoffs, and edge cases sharpens communication fast. Practice with experienced engineering peers or structured mock partners so you catch blind spots before your real interviews.
Questions
When do I use a stack instead of a queue?
Use a stack when the item you need is the most recent one, as with matching brackets, undoing a step or finding the next larger value. Use a queue when the item you need is the one that has waited longest.
Why is a plain list a poor queue?
Removing from the front of an array-based list moves every other element over by one place, which takes time proportional to n. A deque is built to add and remove at both ends in constant time.
What is a monotonic stack?
It is a stack whose values only rise or only fall from bottom to top, kept that way by popping values that can no longer matter. It answers questions like "where is the next larger value" in one pass.
How a session helps
A session with George is a place to code a problem aloud and have the reasoning questioned: why a stack and not a queue, what each element stands for and what happens when the structure is empty. You write all the code yourself. Next, read the data structures checklist and the coding and complexity practice, and use the coding prep schedule to put the topics on a calendar. See the packages page for the sessions, or book a session.
Want help with your own applications? See internship interview coaching, a career coach for college internships, or resume review for internships.