Stack

A structure where the last item added is always the first one removed.

What is it?

Some problems process things in reverse order of arrival: undo history, nested function calls, matching brackets. A stack handles this. You can only add ("push") or remove ("pop") at one end, the top, so the most recent item always comes out first.

This rule is called LIFO: Last In, First Out.

Explain like I'm 10

A stack is like a pile of plates. You add a plate on top and take the top one off first. You'd never pull one from the bottom.

Examples

Using an array as a stack

const stack = [];

stack.push(1); // [1]
stack.push(2); // [1, 2]
stack.push(3); // [1, 2, 3]

console.log(stack.pop()); // 3 — removes and returns the top item
console.log(stack);       // [1, 2]

push and pop both work on the end of the array, which is exactly how a stack behaves. JavaScript needs no special structure.

How it works

A stack has two main operations: push (add to the top) and pop (remove from the top). Both are O(1), since no other item is touched. To reach an item in the middle, you must first remove everything above it.

push(1)   push(2)   push(3)     pop()
   ↓         ↓         ↓          ↓
  [1]      [1,2]    [1,2,3]    returns 3, leaves [1,2]

Why does it exist?

Many real problems are last-in-first-out: undo/redo history, tracking function calls (the call stack!), and checking that brackets are balanced. A stack models that directly.

When to use it

Use a stack when the most recent item must come out first: undo history, matching brackets, or tracking a path while backtracking through a maze or tree.

When not to use it

To process items in arrival order, use a queue instead. And if you often need to inspect or remove items in the middle, the "only touch the top" rule will fight you.

Common mistakes

  • Trying to reach the middle of a stack directly instead of popping down to it.

  • Popping an empty stack without checking first, which causes errors or undefined.

  • Confusing a stack (LIFO) with a queue (FIFO). They solve different problems.

Practice exercises

  1. Easy:

    Implement a Stack class with push, pop and peek (view the top without removing it) methods.

  2. Medium:

    Use a stack to check whether a string of parentheses like "(()())" is balanced.

  3. Hard:

    Use a stack to reverse the words in a sentence without using built-in reverse methods.

Interview questions

What does LIFO mean?

Last In, First Out: the most recently added item is always the first one removed.

What is a real-world use of a stack in programming?

The call stack, which tracks function calls. Also undo/redo, balanced-bracket checking, and browser back/forward-style history.

What's the time complexity of push and pop?

Both O(1). They only touch the top item; nothing shifts or gets scanned.

Compare an array-based stack to a linked-list-based one — what are the real tradeoffs?

An array-based stack is contiguous, so it has better cache locality, but a dynamic array sometimes resizes (an O(n) copy). A linked-list stack guarantees O(1) per operation with no resizing, but uses extra memory for a pointer per node and has worse cache locality.

What does 'amortized O(1)' mean for pushing onto a dynamic array-based stack, given that resizing is O(n)?

When the backing array fills, it usually doubles in capacity, an O(n) copy. Doubling makes resizes rarer as the stack grows, so all resizes across n pushes cost O(n) in total. That's O(1) per push on average, though a single resizing push costs O(n).

What happens if you try to push onto a fixed-capacity array-based stack that's already full?

A fixed-size stack overflows, usually by throwing an error or refusing the push. A dynamic one resizes to a larger backing array first, then completes the push.

Is a call stack overflow the same kind of thing as overflowing a fixed-size custom stack?

Conceptually yes: both exceed the available capacity. The call stack's limit is the memory the OS/engine reserves for stack frames (exceeded by recursing too deeply). A custom stack's limit is whatever capacity its storage was given.

How would you design a stack that supports `push`, `pop`, and `getMin()` (current minimum) all in O(1)?

Keep a second stack that tracks the minimum at each point. On push, also push the smaller of (new value, current top of the min stack) onto it. On pop, pop both stacks. getMin() peeks the min stack's top, no scanning needed.

Trace a min-stack: push 5, push 3, push 7, push 3, pop, pop. What does `getMin()` return after each step?

push 5: main [5], min-stack [5], min=5. push 3: main [5,3], min-stack [5,3], min=3. push 7: main [5,3,7], min-stack [5,3,3] (7 isn't smaller than 3, so 3 repeats), min=3. push 3: main [5,3,7,3], min-stack [5,3,3,3], min=3. pop: removes 3 from both, main [5,3,7], min-stack [5,3,3], min=3. pop: removes 7 from both, main [5,3], min-stack [5,3], min=3. The repeated 3 is what keeps the minimum correct after the top 3 is popped.

How would you evaluate the postfix expression `"3 4 + 2 *"` using a stack?

Scan left to right: push 3, push 4. On +, pop 4 then 3, compute 3 + 4 = 7, push 7. Push 2. On *, pop 2 then 7, compute 7 * 2 = 14, push 14. The stack ends holding only the result, 14.

Why does evaluating postfix notation require a stack instead of computing left to right immediately?

An operator's operands may be results of earlier computations, not just raw numbers. The stack holds every intermediate result until an operator needs it.

How would you check whether a string like `"{[()]}"` has properly balanced brackets, using a stack?

Push each opening bracket. On a closing bracket, pop and check it matches; if it doesn't (or the stack is empty), the string is unbalanced. At the end, it's balanced only if the stack is empty.

Why does checking `"([)]"` for balance require tracking order with a stack, rather than just counting each bracket type?

In "([)]" the counts of (, ), [ and ] all match, but the nesting is wrong: ) arrives before the inner [ is closed. A stack catches this: when ) arrives, the top is [, which doesn't match.

How would you implement a queue using two stacks?

Push to an 'in' stack to enqueue. To dequeue, if the 'out' stack is empty, pop everything from 'in' onto 'out'. This reverses the order, putting the oldest item on top of 'out'. Then pop from 'out'. If 'out' isn't empty, pop from it directly.

What's the amortized time complexity of dequeue in the two-stack queue, even though one dequeue can move every element between stacks?

Amortized O(1). Each element is pushed onto 'in' once and moved to 'out' at most once, so n operations make at most about 2n moves. That averages O(1) per operation, though one dequeue can occasionally cost O(n).

What is the 'next greater element' problem, and how does a stack solve it in O(n) instead of O(n²)?

For each element, find the first larger element to its right. Checking every pair is O(n²). Instead, scan left to right with a stack of indices still waiting for an answer. While the current value is bigger than the top's value, pop that index and record the current value as its answer. Each index is pushed and popped at most once: O(n).

How would you reverse a string (or a list's order) using a stack, and what's the space cost?

Push every item, then pop them all; a stack reverses insertion order. It costs O(n) extra space, since every element sits on the stack at once.

Why should code check whether a stack is empty before calling `pop()` or `peek()`?

An empty stack has no top item. Depending on the implementation, it may throw, return undefined, or (in a fixed-size array with an index counter) underflow the counter into an invalid state. Checking first avoids all of these.

How is the call stack itself an instance of the abstract stack data structure?

Each function call pushes a frame with its local variables, parameters and return address. On return, the frame is popped and the caller resumes at that address. The most recently called, unfinished function always finishes next: LIFO.

How would you convert a recursive function into an iterative one using an explicit stack, and why does this always work?

Keep your own stack of pending work (the arguments or state each recursive call would use). Loop: pop a unit of work, process it, and push any new work instead of recursing. It works because recursion itself runs on the call stack, so your own stack can simulate the same call-and-return behavior.

How does a browser's back/forward navigation map onto stack operations?

Visiting a new page pushes it onto a 'back' stack and usually clears the 'forward' stack, since that branch of history is no longer valid. Back pops from 'back' and pushes onto 'forward'. Forward does the reverse.

Why is peeking at a stack's top O(1), but checking whether a value exists anywhere in the stack O(n)?

Peek reads one element, the top, whatever the size. Only the top is reachable, so finding any other value may mean inspecting (or popping) every element.

What's the difference between a stack overflow and a stack underflow?

Overflow is exceeding capacity: pushing past a fixed-size stack's limit, or recursing until the call stack runs out of memory. Underflow is popping or peeking an empty stack.

Scenario: you're building undo/redo. Why use two separate stacks instead of one?

Undo pops an action off the undo stack, but that action must stay available to redo, so it's pushed onto a separate redo stack. One stack can't hold both 'actions to undo' and 'undone actions to reapply' as two independent sequences.

How would you sort a stack into ascending order using only one additional stack?

Pop each element from the original stack. Move elements from the sorted stack back onto the original until the sorted stack's top is not greater than the current element, then push the element onto the sorted stack. When the original is empty, the other stack is sorted. It's O(n²), since each insertion may reshuffle much of the sorted stack.

Why is a stack the natural structure for validating that HTML/XML tags are properly nested and closed?

Push each opening tag. Each closing tag must match the most recent unclosed tag, which is the stack's top. Popping and comparing on every closing tag checks nesting, just like bracket matching.