AlgoDaily

Stacks and Queues

Read at your own pace. Code execution, quizzes, progress tracking, and the AI tutor are available in the interactive view with JavaScript enabled.

Why This Matters

From pointers to controlled access

Now that you've finished Arrays and Strings and Linked Lists, you know two important ways data can be laid out: contiguous blocks and node chains.

Today we add two interview-favorite access rules on top of collections:

  • Stack: last item in is the first item out
  • Queue: first item in is the first item out

These show up constantly in MAANG-style interviews because they model real workflows: undo history, browser navigation, task scheduling, parsing expressions, and level-by-level processing.

We will stay focused on the core structures and Java usage. Later lessons like Trees and Graphs will reuse queues heavily, but we won't jump ahead yet.

Why This Matters

Stack Mental Model

Stack = LIFO

A stack follows LIFO:

Last In, First Out

Think of a stack of plates. You add a plate on top, and you also remove from the top.

Top
 ↓
[ 30 ]  ← pop removes this first
[ 20 ]
[ 10 ]  ← bottom

Core operations:

  • push(x) — add x to the top
  • pop() — remove and return the top
  • peek() — read the top without removing
  • isEmpty() — check if no items remain

For interviews, the key idea is not the syntax. It is the restriction: you only interact with the most recent item.

Stack Mental Model

Stack In Java

Prefer ArrayDeque for stacks

Java has an old Stack class, but in modern interview and production-style Java, prefer:

  • Deque<Integer> stack = new ArrayDeque<>();

Use these stack-style methods:

  • push(x)
  • pop()
  • peek()

Each is O(1) on average for ArrayDeque.

```java
import java.util.ArrayDeque;
import java.util.Deque;

public class Main {
    public static void main(String[] args) {
        Deque<Integer> stack = new ArrayDeque<>();

        stack.push(10);
        stack.push(20);
        stack.push(30);

        System.out.println("Top item: " + stack.peek());
        System.out.println("Removed: " + stack.pop());
        System.out.println("New top: " + stack.peek());
        System.out.println("Stack now: " + stack);
    }
}
```

Stack Check

A stack receives these operations:

push(5)
push(8)
push(2)
pop()
pop()

Which value is returned by the second pop()?

Queue Mental Model

Queue = FIFO

A queue follows FIFO:

First In, First Out

Think of a line at a coffee shop. The first person to enter the line is served first.

Front                         Back
 ↓                             ↓
[ 10 ] → [ 20 ] → [ 30 ] → [ 40 ]
 poll()                    offer(50)

Core operations:

  • offer(x) — add x to the back
  • poll() — remove and return the front
  • peek() — read the front without removing
  • isEmpty() — check if no items remain

The queue restriction is: you process the oldest waiting item first.

Queue Mental Model

Queue In Java

ArrayDeque works for queues too

The same ArrayDeque can act as a queue when you use queue-style methods:

  • offer(x) to enqueue
  • poll() to dequeue
  • peek() to inspect the front

This is one reason ArrayDeque is worth knowing early: it supports both stack and queue behavior cleanly.

```java
import java.util.ArrayDeque;
import java.util.Queue;

public class Main {
    public static void main(String[] args) {
        Queue<String> queue = new ArrayDeque<>();

        queue.offer("Alice");
        queue.offer("Bob");
        queue.offer("Cara");

        System.out.println("Next served: " + queue.peek());
        System.out.println("Serving: " + queue.poll());
        System.out.println("Serving: " + queue.poll());
        System.out.println("Still waiting: " + queue);
    }
}
```

Queue Truth

True or false?

In a queue, the most recently added element is always removed first.

Classic Stack Pattern

Matching parentheses

One of the most common stack interview patterns is:

Use a stack when you need to remember the most recent unresolved item.

For balanced brackets, every closing bracket must match the most recent opening bracket.

Example:

({[]})  ✅ balanced
([)]    ❌ not balanced

Why stack? Because the last opening bracket must be closed first.

```java
import java.util.ArrayDeque;
import java.util.Deque;

public class Main {
    public static boolean isBalanced(String s) {
        Deque<Character> stack = new ArrayDeque<>();

        for (char ch : s.toCharArray()) {
            if (ch == '(' || ch == '[' || ch == '{') {
                stack.push(ch);
            } else if (ch == ')' || ch == ']' || ch == '}') {
                if (stack.isEmpty()) return false;

                char open = stack.pop();
                if (ch == ')' && open != '(') return false;
                if (ch == ']' && open != '[') return false;
                if (ch == '}' && open != '{') return false;
            }
        }

        return stack.isEmpty();
    }

    public static void main(String[] args) {
        System.out.println("({[]}) -> " + isBalanced("({[]})"));
        System.out.println("([)] -> " + isBalanced("([)]"));
        System.out.println("((())) -> " + isBalanced("((()))"));
    }
}
```

Java Blank

Fill in the blank:

In modern Java, a common choice for implementing both stack-like and queue-like behavior is ________.

Interview Takeaways

What to remember

Stacks and queues are simple, but interviewers use them to test whether you can choose the right access pattern.

Use a stack when...
  • You need most recent first behavior
  • You are handling nested or reversible actions
  • You need to track unresolved items, like open brackets
Use a queue when...
  • You need oldest first behavior
  • You are simulating waiting lines or task processing
  • You need fair ordering by arrival time
Complexity

For ArrayDeque:

  • Push / pop / peek: O(1)
  • Offer / poll / peek: O(1)
  • Space: O(n) for stored elements

Next, we'll move from linear structures into Trees and Graphs, where these same ideas become building blocks for traversals.

Interview Takeaways

Open interactive view →