Skip to main content
LeetCode Prep
CHAPTER 07 Beginner

Stack and Queue Problems

Updated: May 18, 2026
5 min read

# 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.
*Implementation:* In Python and JavaScript, a standard Array/List functions perfectly as a Stack using 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. 1. Iterate through the string.
  1. 2. If it's an Open Bracket, Push it onto the stack.
  1. 3. If it's a Closed Bracket, look at the Peek of the stack. Does it match?
  • If yes, Pop the top element and continue.
  • If no, or if the stack is empty, return False.
  1. 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.

python
12345678910111213
def dailyTemperatures(temps):
    res = [0] * len(temps)
    stack = [] # Stores indices, not the actual temperatures
    
    for i, t in enumerate(temps):
        # While stack is not empty and current temp is > top of stack temp
        while stack and t > temps[stack[-1]]:
            stack_idx = stack.pop()
            res[stack_idx] = i - stack_idx # Calculate days waited
        stack.append(i)
        
    return res
# Time: O(N), Space: O(N)

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 from historyStack and push it to forwardStack.
  • When you hit the "Forward" button, pop from forwardStack and push it to historyStack.

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) > 0 or if not stack.isEmpty() before calling pop() or peek(), otherwise your code will crash with an Exception.
  • Using arrays for Queues: As stated, list.pop(0) in Python or ArrayList.remove(0) in Java is O(N) Time. This will fail performance tests. Use Deque or LinkedList.

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. 1. Trace the Valid Parentheses logic on the string "{[()]}".
  1. 2. Trace the Valid Parentheses logic on the string "{[(])}". At what exact point does the algorithm fail?

12. MCQs

Question 1

What is the fundamental difference between a Stack and a Queue?

Question 2

What is the Time Complexity of pushing an item onto a Stack, and popping an item off a Stack?

Question 3

When solving the "Valid Parentheses" problem, what action do you take when you encounter a closing bracket (e.g., }) ?

Question 4

Why is using a standard Array/List to simulate a Queue (list.pop(0)) a terrible idea in an interview?

Question 5

What is a "Monotonic Stack"?

Question 6

What specific class of problems is the Monotonic Stack designed to solve in O(N) Time?

Question 7

When building a Monotonic Stack to calculate the distance (number of days/steps) between elements, what exactly should you push onto the stack?

Question 8

What critical edge case must you always check before calling .pop() or .peek() on a Stack?

Question 9

Which algorithmic traversal relies fundamentally on a Queue (FIFO)?

Question 10

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?
A: No. Unless the interviewer specifically asks you to implement a data structure from scratch, use the built-in language structures (Lists in Python, ArrayDeque in Java).

16. Summary

Stacks (LIFO) and Queues (FIFO) define the strict order in which data is processed. Use Stacks for matching pairs (Parentheses), undo operations (Browser History), or remembering deferred processing (Monotonic Stacks for "Next Greater Element"). Use Queues for processing data in the exact order it arrived, which is the foundation of BFS. Always check if the structure is empty before popping to prevent crashes.

17. Next Chapter Recommendation

Stacks and Queues are often backed by Arrays. But what if we want to store data scattered randomly across memory, connected by pointers? In Chapter 8: Linked List Problems, we will explore Node traversal, reversal, and pointer manipulation.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·