Stacks & Queues Exercises: Practice Problems
Time to practice stacks and queues. Solve each problem yourself first — write the code, trace a small example by hand, and reason about time and space. Only then open the answer sheet. Every View answer link jumps to a full, multi-language solution on the stacks & queues solutions page.
How to practice: Set a timer (15–25 min per problem). Stuck? Re-read stacks, queues, or the monotonic stack before peeking. The struggle is what makes the pattern stick.
Warm-ups
Q1. Reverse a string using a stack. Given a string, return it reversed using a stack (push every character, then pop them all). Target O(n) time and O(n) space. Why does a stack reverse order for free?
Q2. Valid parentheses. Given a string containing only ()[]{}, return true if every bracket is closed by the matching type in the correct order. Target O(n) time.
Core problems
Q3. Implement a queue using two stacks. Build a FIFO queue exposing enqueue and dequeue, using only two stacks internally. What is the amortized cost of dequeue?
Q4. Min Stack. Design a stack supporting push, pop, top, and getMin — all in O(1) time. Hint: store the running minimum alongside each element.
Q5. Next Greater Element. For each element of an array, find the next element to its right that is strictly larger, or -1 if none. Aim for a single O(n) pass with a monotonic stack.
Challenge
Q6. Implement a stack using two queues. Build a LIFO stack exposing push and pop, using only two queues internally. Make push (or pop) O(n) and the other O(1) — state which you chose.
Q7. Sliding window maximum. Given an array and a window size k, return the maximum of every contiguous window of size k. Target O(n) time using a monotonic deque.
Done? Review every solution on the answer sheet — even the ones you solved, since there is often a cleaner approach. Then continue to hashing.