Stack introduction

Stacks

A stack is a last-in, first-out (LIFO) collection. You can only add to the top (push) and remove from the top (pop). Think of a stack of plates: the last one you put down is the first one you pick up.

In Go

A plain slice is all you need:

stack = []
stack.push(x)                       // push
top = stack[length(stack) - 1]      // peek
stack.pop()                         // pop

Always check len(stack) > 0 before peeking or popping.

When to reach for a stack

Stacks shine whenever the most recent unfinished thing is what you need next:

  • Matching pairs — brackets, parentheses, tags. Push openers; on a closer, the top must be its match.
  • Reversing — push everything, pop it back out in reverse order.
  • Nesting — track the current context and restore the previous one when a nested section ends (decompressing 2{ab}, scoring [[]]).
  • Undo / backtracking — the last action is the first to undo.

Cost

Push, pop, and peek are all O(1). A single left-to-right pass that pushes and pops each element a constant number of times is O(n). The art is recognising the LIFO structure hiding in a problem — the exercises in this section train exactly that.