Jaconir
Skip to lesson
easy
20 minMostly intern / new-grad

When to use. Stack: reverse order, matching, undo, DFS. Queue: level order, BFS, sliding-window queues.

Complexity. Time Push/pop/enqueue/dequeue O(1) amortized. Space O(n) for the items you hold.

Who gets asked. Interns implement and use them. Later rounds assume you pick a stack or queue without being asked.

Prereq. Arrays or linked lists as the backing store.

Stacks & Queues: Orderly Data

Learn about two fundamental data structures that manage collections of items in a specific order.

What Is a Stack? (LIFO)

A stack is a "Last-In, First-Out" (LIFO) data structure. Imagine a stack of plates: the last plate you put on top is the first one you take off. Stacks have two primary operations:

  • Push: Adds an item to the top of the stack.
  • Pop: Removes the item from the top of the stack.

This structure is incredibly useful for tasks like managing function calls (the call stack) in programming, implementing the "undo" functionality in an editor, or handling a browser's back-button navigation history.

What Is a Queue? (FIFO)

A queue is a "First-In, First-Out" (FIFO) data structure. Think of a line at a grocery store: the first person to get in line is the first person to be served. Queues have two main operations:

  • Enqueue: Adds an item to the back of the queue.
  • Dequeue: Removes the item from the front of the queue.

In frontend development, this concept is similar to the browser's event loop, which processes user interactions (like clicks) and rendering updates in the order they are received. It's also used for breadth-first search in graph algorithms. Interns implement stacks for matching brackets. The 2026 follow-up is a monotonic stack (next greater in O(n)) and queues for BFS.

Interactive Stack (LIFO)
Last-In, First-Out. Think of a stack of plates.
C
B
A
Interactive Queue (FIFO)
First-In, First-Out. Think of a checkout line.
FRONT
A
B
C
BACK
Problem: matching brackets
Use a stack to check that every opener is closed by the matching type in order (e.g. `()`, `[]`, `()`).
{[()]}
Start with an empty stack.
function isValid(s) {
  const stack = [];
  const map = {
    "(": ")",
    "[": "]",
    "{": "}",
  };

  for (let i = 0; i < s.length; i++) {
    const char = s[i];
    if (map[char]) {
      stack.push(char);
    } else {
      if (stack.length === 0) {
        return false;
      }
      const lastOpen = stack.pop();
      if (map[lastOpen] !== char) {
        return false;
      }
    }
  }

  return stack.length === 0;
}
Coding Challenge
A string of (), {}, and []. Every opener must close with the matching type, in the right order. Stack, O(n) time and space.
Quick Quiz: Test Your Knowledge

A web browser's "Back" button functionality is best implemented using a:

A print queue that prints jobs in the order they were submitted is an example of a:

A function call stack in a programming language follows which principle?

Saved in this browser. No account.