Back to DSA Guide Catalog

Data Structureeasy

Stack (LIFO) Complete Guide

Stack is LIFO (last-in, first-out). The newest item is always removed first.

It maps naturally to nested structure handling: expressions, undo history, recursion simulation, and syntax validation.

When a problem needs 'most recent unresolved item', stack is usually the right fit.

Typical Complexity Baseline

MetricValue
Push/pop/topO(1)

Video Explainer

Prefer video learning? This explainer gives a quick visual walkthrough of the core idea before you dive into the detailed sections below.

Core Concepts

Learn the core building blocks and terminology in one place before comparisons, so the mechanics are clear and duplicates are removed.

Top

What it is: Current most recent element.

Why it matters: Top is a required building block for understanding how Stack (LIFO) stays correct and performant on large inputs.

Push

What it is: Insert new item on top.

Why it matters: Push is a required building block for understanding how Stack (LIFO) stays correct and performant on large inputs.

Pop

What it is: Remove and return top item.

Why it matters: Pop is a required building block for understanding how Stack (LIFO) stays correct and performant on large inputs.

Peek

What it is: Read top item without removal.

Why it matters: Peek is a required building block for understanding how Stack (LIFO) stays correct and performant on large inputs.

Monotonic invariant

What it is: Optional ordering rule used in many optimization problems.

Why it matters: Monotonic invariant is a required building block for understanding how Stack (LIFO) stays correct and performant on large inputs.

LIFO

What it is: Last item added is first item removed.

Why it matters: Last item added is first item removed. In Stack (LIFO), this definition helps you reason about correctness and complexity when inputs scale.

Monotonic Stack

What it is: Stack that stays increasing/decreasing to optimize comparisons.

Why it matters: Stack that stays increasing/decreasing to optimize comparisons. In Stack (LIFO), this definition helps you reason about correctness and complexity when inputs scale.

Sentinel

What it is: Dummy value to simplify boundary handling.

Why it matters: Dummy value to simplify boundary handling. In Stack (LIFO), this definition helps you reason about correctness and complexity when inputs scale.

Underflow

What it is: Pop/peek attempted on empty stack.

Why it matters: Pop/peek attempted on empty stack. In Stack (LIFO), this definition helps you reason about correctness and complexity when inputs scale.

Call stack

What it is: Runtime-managed stack of active function frames.

Why it matters: Runtime-managed stack of active function frames. In Stack (LIFO), this definition helps you reason about correctness and complexity when inputs scale.

Putting It All Together

This walkthrough connects the core concepts of Stack (LIFO) into one end-to-end execution flow.

Step 1

Top

Current most recent element.

Before

Stack top

empty
  • Operation: push(3), push(7)

After

Stack top

73
  • LIFO order maintained

Transition

Append 3
Append 7 on top

Why this step matters: Top is a required building block for understanding how Stack (LIFO) stays correct and performant on large inputs.

Step 2

Push

Insert new item on top.

Before

Stack top

73
  • Operation: pop()

After

Stack top

3
  • Popped: 7

Transition

Remove top element only
Do not touch lower entries

Why this step matters: Push is a required building block for understanding how Stack (LIFO) stays correct and performant on large inputs.

Step 3

Pop

Remove and return top item.

Before

Input: "()

empty
  • {}"
  • Need valid-parentheses check

After

  • Stack ended empty
  • Expression valid = true

Transition

Push open brackets
Pop when matching close appears

Why this step matters: Pop is a required building block for understanding how Stack (LIFO) stays correct and performant on large inputs.

Step 4

Peek

Read top item without removal.

Before

  • Call stack depth: 0
  • Evaluate recursive DFS

After

  • All frames released
  • Traversal complete

Transition

Push frame per recursive call
Pop on return

Why this step matters: Peek is a required building block for understanding how Stack (LIFO) stays correct and performant on large inputs.

How It Compares

vs Queue

When to choose this: Choose stack when most-recent-first semantics are required.

Tradeoff: Queue is better for first-in-first-out processing.

vs Recursion

When to choose this: Choose explicit stack when recursion depth may exceed safe limits.

Tradeoff: Recursion can be cleaner for tree-like code.

vs Array scan

When to choose this: Choose stack when unresolved prior states must be revisited.

Tradeoff: Simple scan is better when no backtracking state is needed.

Real-World Stories and Company Examples

Google

Compiler and parser stacks track nested syntax while converting source code into internal representations.

Takeaway: Nested language constructs map directly to stack operations.

Figma

Undo/redo stacks maintain operation history for interactive editing sessions.

Takeaway: LIFO behavior provides intuitive user-facing history controls.

Browsers

JavaScript engines and layout systems track nested execution and traversal states with stack structures.

Takeaway: Stacks are foundational for runtime correctness.

Implementation Guide

Push open brackets, pop on close bracket, and ensure expected pair type.

Complexity: Time O(n), Space O(n)

Valid parentheses with stack

function isValidParentheses(text: string): boolean {
  const stack: string[] = []
  const expectedOpenByClose: Record<string, string> = { ')': '(', ']': '[', '}': '{' }

  for (const char of text) {
    if (char === '(' || char === '[' || char === '{') {
      stack.push(char)
      continue
    }
    const expectedOpen = expectedOpenByClose[char]
    if (!expectedOpen) continue
    if (stack.pop() !== expectedOpen) return false
  }

  return stack.length === 0
}

Common Problems and Failure Modes

  • Popping without checking empty state.
  • Using stack where queue semantics are needed.
  • Missing equal-value handling in monotonic stack logic.
  • Confusing character index with character value in parser tasks.
  • Recursive solution without depth safeguards.

Tips and Tricks

  • Stack is the default choice for 'most recent unresolved item' problems.
  • For monotonic stack questions, decide monotonic direction first, then implement push/pop rules.
  • Use sentinel values to simplify empty-stack edge conditions.
  • If recursion depth might explode, convert recursion to explicit stack iteration.

When to Use

Use these signals to decide if this data structure/algorithm is the right fit before implementation.

Real-system usage signals

  • Simple push/pop API with O(1) operations.
  • Natural model for nested parentheses and parser state.
  • Useful for monotonic patterns and backtracking breadcrumbs.

LeetCode-specific tips (including pattern-identification signals)

  • Identification signal: last opened item must close first (parentheses, nested structures, undo/history behavior).
  • Identification signal: you need to process nearest previous/next greater-smaller relationships while scanning once.
  • If the solution needs push/pop symmetry with strict LIFO order, choose stack before queue or map.
  • For Stack (LIFO) questions, start by naming the core invariant before writing code.
  • Use the constraint section to set time/space target first, then pick the data structure/algorithm.
  • Solve one tiny example by hand and map each transition to your variables before implementing.
  • Run adversarial cases: empty input, duplicates, max-size input, and sorted/reverse patterns when relevant.
  • During interviews, explain why your approach is the right pattern for this prompt, not just why the code works.

LeetCode Progression (Easy to Hard)

Back to DSA Guide Catalog
#ProblemDifficultyTypical Complexity
1Valid ParenthesesEasyO(n)
2Implement Stack using QueuesEasyO(n) worst push
3Min StackMediumO(1) ops
4Evaluate Reverse Polish NotationMediumO(n)
5Daily TemperaturesMediumO(n)
6Car FleetMediumO(n log n)
7Largest Rectangle in HistogramHardO(n)
8Trapping Rain WaterHardO(n)
9Basic CalculatorHardO(n)
10Remove K DigitsHardO(n)