beginnerdata-structures

Stacks

Stacks

A stack is a linear data structure that follows the Last-In, First-Out (LIFO) principle. Think of a stack of plates — you can only add or remove plates from the top. The last plate placed on top is the first one you take off. This simple constraint makes stacks surprisingly powerful for solving many programming problems.

Core Operations

OperationDescriptionTime Complexity
push(item)Add an element to the topO(1)
pop()Remove and return the top elementO(1)
peek() / top()View the top element without removing itO(1)
is_empty()Check if the stack is emptyO(1)
size()Return the number of elementsO(1)

All operations run in constant time because they only interact with the top of the stack.

How It Works

  1. Push: Place a new element on top of the stack. Increment the top pointer.
  2. Pop: Remove the element at the top. Decrement the top pointer. Return the removed element.
  3. Peek: Read the element at the top without modifying the stack.

The stack maintains a single pointer (or index) tracking the current top position. No searching, shifting, or reordering is ever needed.

Step-by-Step Example

Starting with an empty stack:

push(10) → Stack: [10]         (top = 10)
push(20) → Stack: [10, 20]    (top = 20)
push(30) → Stack: [10, 20, 30] (top = 30)
pop()    → Returns 30, Stack: [10, 20] (top = 20)
peek()   → Returns 20, Stack: [10, 20] (unchanged)
pop()    → Returns 20, Stack: [10] (top = 10)

Code Snippet

class Stack:
    """Stack implementation using a Python list."""

    def __init__(self):
        self._items = []

    def push(self, item) -> None:
        """Add an element to the top of the stack."""
        self._items.append(item)

    def pop(self):
        """Remove and return the top element. Raises error if empty."""
        if self.is_empty():
            raise IndexError("Pop from empty stack")
        return self._items.pop()

    def peek(self):
        """Return the top element without removing it."""
        if self.is_empty():
            raise IndexError("Peek at empty stack")
        return self._items[-1]

    def is_empty(self) -> bool:
        """Check if the stack has no elements."""
        return len(self._items) == 0

    def size(self) -> int:
        """Return the number of elements in the stack."""
        return len(self._items)

Classic Problem: Balanced Parentheses

One of the most common stack applications is checking whether brackets are balanced:

def is_balanced(expression: str) -> bool:
    """Check if parentheses, brackets, and braces are balanced."""
    stack = []
    opening = "({["
    closing = ")}]"
    pairs = {")": "(", "}": "{", "]": "["}

    for char in expression:
        if char in opening:
            stack.append(char)
        elif char in closing:
            if not stack or stack[-1] != pairs[char]:
                return False
            stack.pop()

    return len(stack) == 0

Complexity Analysis

Time Complexity: O(1) per operation

Every stack operation (push, pop, peek) takes constant time. There's no traversal — you always work with the top element directly.

Space Complexity: O(n)

The stack uses space proportional to the number of elements stored. If you push n items, you need O(n) space.

When to Use Stacks

  • Function call management: Every programming language uses a call stack to track function invocations, local variables, and return addresses.
  • Undo/Redo operations: Text editors push each action onto a stack. Undo pops the last action; redo uses a second stack.
  • Expression evaluation: Compilers and calculators use stacks to evaluate arithmetic expressions and convert between infix, prefix, and postfix notation.
  • Backtracking algorithms: DFS, maze solving, and puzzle solvers use stacks (explicitly or via recursion) to track the path and backtrack when stuck.
  • Browser history: The back button uses a stack of previously visited pages.
  • Syntax parsing: Compilers use stacks to match brackets, validate HTML tags, and parse nested structures.

Stack vs. Queue

PropertyStack (LIFO)Queue (FIFO)
OrderLast in, first outFirst in, first out
AddPush to topEnqueue to back
RemovePop from topDequeue from front
Use caseUndo, DFS, parsingBFS, scheduling, buffering

Array vs. Linked List Implementation

  • Array-based (shown above): Simple, cache-friendly, amortized O(1) push. May need resizing.
  • Linked list-based: O(1) push/pop without resizing, but uses extra memory for node pointers and has worse cache performance.

For most applications, the array-based implementation is preferred.

Key Properties

PropertyValue
Access patternLIFO (Last-In, First-Out)
Push/PopO(1)
Random accessNot supported
Thread-safeNo (requires synchronization)