Stack and Queue Problems
# CHAPTER 7
Stack and Queue Problems
1. Chapter Introduction
When evaluating a math expression(2 + (3 * 4)), how does the computer know which parenthesis matches which? When a printer receives 5 print jobs, how does it know which one to print first? The answers lie in Stacks and Queues. These are ordered data structures that control exactly *when* an item is removed. This chapter covers LIFO, FIFO, and the highly-tested "Monotonic Stack" pattern.
2. The Stack (LIFO: Last-In, First-Out)
Imagine a stack of dirty plates. You put a new plate on the Top. When you wash a plate, you take it from the Top. The last plate you put down is the first one you pick up.- Push(): Add an item to the top. O(1) Time.
- Pop(): Remove the top item. O(1) Time.
- Peek(): Look at the top item without removing it. O(1) Time.
append() and pop(). In Java, use Deque<Integer> stack = new ArrayDeque<>();.
3. Pattern 1: Valid Parentheses
This is a mandatory interview question (LeetCode #20). *Prompt:* Given a string containing just the characters'(', ')', '{', '}', '[' and ']', determine if the input string is valid (every open bracket is closed by the same type of bracket in the correct order).
*The Logic:*
- 1. Iterate through the string.
-
2.
If it's an Open Bracket,
Pushit onto the stack.
-
3.
If it's a Closed Bracket, look at the
Peekof the stack. Does it match?
-
If yes,
Popthe top element and continue.
- If no, or if the stack is empty, return False.
- 4. At the end, if the stack is empty, return True.
4. Pattern 2: The Monotonic Stack (Advanced)
A Monotonic Stack is a stack whose elements are always completely sorted (either strictly increasing or strictly decreasing). *Use Case:* "Next Greater Element" problems. E.g., Given a list of daily temperatures[73, 74, 75, 71, 69, 72, 76], how many days do you have to wait until a warmer temperature?
*The Decreasing Stack Logic:*
We push elements onto the stack. If we encounter a new temperature that is *warmer* than the temperature at the top of the stack, we have found the "Next Greater Element" for that top item! We Pop the top item, calculate the distance, and repeat until the stack is monotonic (decreasing) again.
5. The Queue (FIFO: First-In, First-Out)
Imagine a line at a coffee shop. The first person in line gets their coffee first.- Enqueue/Push: Add to the back of the line. O(1) Time.
- Dequeue/Pop: Remove from the front of the line. O(1) Time.
*Implementation Warning:* In Python, if you use a standard List arr.pop(0) to remove the first element, it is O(N) Time, because every other element must shift forward. You MUST use collections.deque to achieve O(1) Queue operations.
6. When to use a Queue
Queues are the fundamental data structure powering Breadth-First Search (BFS) on Trees and Graphs (covered in Chapter 10). If you need to process data level-by-level, or in the exact order it was received, use a Queue.7. Real-World Scenario: The Browser History
*Prompt:* Design the "Back" and "Forward" buttons of a web browser. *Solution:* Use Two Stacks.-
historyStack: When you visit a new page, push the current page here.
-
forwardStack: When you hit the "Back" button, pop fromhistoryStackand push it toforwardStack.
-
When you hit the "Forward" button, pop from
forwardStackand push it tohistoryStack.
8. Mini Project: Evaluate Reverse Polish Notation
*Prompt:* Evaluate a mathematical expression in postfix notation:["2", "1", "+", "3", "*"].
(This evaluates to ((2 + 1) * 3) = 9).
*Logic:*
Iterate through the array. If it's a number, push to stack. If it's an operator (+, -), pop the top two numbers from the stack, apply the operator, and push the result back onto the stack.
9. Common Mistakes
-
Popping an Empty Stack: Always check
if len(stack) > 0orif not stack.isEmpty()before callingpop()orpeek(), otherwise your code will crash with an Exception.
-
Using arrays for Queues: As stated,
list.pop(0)in Python orArrayList.remove(0)in Java is O(N) Time. This will fail performance tests. UseDequeorLinkedList.
10. Best Practices
- Stacking Indices: When building a Monotonic Stack to calculate distances or spans, push the *Index* of the element onto the stack, not the value itself. You can always use the index to look up the value in the array, but you cannot use the value to look up the index.
11. Exercises
-
1.
Trace the
Valid Parentheseslogic on the string"{[()]}".
-
2.
Trace the
Valid Parentheseslogic on the string"{[(])}". At what exact point does the algorithm fail?
12. MCQs
What is the fundamental difference between a Stack and a Queue?
What is the Time Complexity of pushing an item onto a Stack, and popping an item off a Stack?
When solving the "Valid Parentheses" problem, what action do you take when you encounter a closing bracket (e.g., }) ?
Why is using a standard Array/List to simulate a Queue (list.pop(0)) a terrible idea in an interview?
What is a "Monotonic Stack"?
What specific class of problems is the Monotonic Stack designed to solve in O(N) Time?
When building a Monotonic Stack to calculate the distance (number of days/steps) between elements, what exactly should you push onto the stack?
What critical edge case must you always check before calling .pop() or .peek() on a Stack?
Which algorithmic traversal relies fundamentally on a Queue (FIFO)?
How does a calculator use a Stack to evaluate "Reverse Polish Notation" (e.g., ["2", "1", "+", "3", "*"])?
14. Interview Questions
- Q: "Design a Stack that supports push, pop, top, and retrieving the minimum element in constant O(1) time." (LeetCode 155 - Min Stack. Hint: You need to store tuples or use two parallel stacks).
15. FAQs
- Q: Should I build my own Stack class from scratch in an interview?