Layers of Logic

Foundation 05

Stack

A last-in, first-out collection: only the most recently added item is exposed.

Core2 operations comparedJava · Python · C++

What the structure guarantees

The restricted access is the useful part. The top always represents the most recent unresolved item, call, edit, opening bracket, or candidate answer.

How that model appears in code

Java code should normally use ArrayDeque rather than the legacy Stack class. C++ has std::stack; Python lists support append and pop at the end.

Stack basics

Deque<Integer> stack = new ArrayDeque<>();
stack.push(7);
int top = stack.peek();
int removed = stack.pop();

What gets more expensive as the input grows

OperationCostWhy
Push, peek, or pop the topO(1)Only one end changes.
Search for an arbitrary itemO(n)The stack offers no direct middle access.

Choose it for the operations it makes cheap

Good fit

  • Nested delimiters
  • Undo and backtracking
  • Unresolved candidates in monotonic-stack problems

Poor fit

  • Oldest-first processing
  • Random access
  • Removing from the middle

Used by

Monotonic Stack

Errors that survive a first glance

  1. Check for empty before peek or pop

    Put the emptiness test first in a short-circuit condition.

  2. Store indices when distance matters

    An index can recover both the value and the distance. A value alone cannot recover its position.

  3. Use one end consistently

    Mixing front and back operations quietly changes the data structure.