Esc
  • Loading…
↑ ↓ to moveEnter to openEsc to close

Stack

Learn the last-in, first-out structure behind undo, the call stack and every calculator — then solve the 13 stack questions interviews ask most.

  • 6 Lessons
  • 13 Problems
  • 78 Illustrations

Dry-run engine

Valid Parentheses

A stack is a fixed buffer plus a single top index — push and pop never move anything else.

O(n) Memory
Input
s = "([]{})"
Output · Returns
Press play to run it
How it works

Push every opening bracket. On a closing bracket, pop and check it matches. The string is balanced only if every pop matches and top ends at -1.

stack_buffer[4]

  • i—
  • top-1
  • Action—

The stack is a fixed buffer plus one integer, top = -1 (empty). Push writes buf[++top]; pop reads buf[top--] — neither ever shifts memory.

1 / 8

What you will learn

  • What a stack is, why only the top is ever touched, and what underflow and overflow mean
  • Why stacks exist, from the call stack and recursion to undo, brackets and backtracking
  • When a problem is secretly a stack problem: matching, cancelling, undoing and "the nearest bigger"
  • How to use the built-in stack in JavaScript, Python, Java and C++, and build your own on a linked list
  • Infix, prefix and postfix notation, and the monotonic stack pattern behind the hardest questions
  • Brute force, optimal and best solutions for 13 interview questions, each with a dry-run simulator

Why this course

A stack only lets you touch the top: push something on, pop the last thing off. That one rule turns out to be exactly what you need whenever the most recent thing matters most — the latest open bracket, the function that was called last, the last edit you want to undo.

The course starts with what a stack is, why it exists, when to use one and how to build one, then two ideas the interview questions lean on: prefix, infix and postfix notation, and the monotonic stack. Every idea is drawn, and every lesson has a simulator you can step through.

Then you solve the 13 most asked stack interview questions — implementations, bracket matching, a min & max stack, expression conversions, next greater elements, asteroid collisions, decoding strings, the largest rectangle in a histogram and trapping rain water. Every problem goes from brute force to optimal to the best solution, with code in four languages.

Requirements

  • Comfort writing loops, conditionals and functions in at least one language
  • The Arrays course, or equivalent familiarity with arrays and indexes
  • The Linked List course helps for one lesson (a stack built on nodes), but isn't required

Course Contents