Previous Topic
underlying_implementation
0.86
Simple linked lists provide node-based, dynamic storage with constant-time head updates that directly realize stack semantics.
concept
0.85
Stacks and queues, as a combined concept, encompass the specific data structure of stacks, which operate on a LIFO basis.

Stacks

data structures algorithms programming software engineering operating systems computer science
A stack is a fundamental linear data structure that follows the Last-In, First-Out (LIFO) principle. Items are added and removed only from the top, supporting fast push, pop, and peek operations. Stacks are widely used in algorithms, language runtimes (call stacks), parsing, backtracking, and undo/redo features.

What Is a Stack?

A stack is a linear data structure that enforces Last-In, First-Out (LIFO) ordering: the most recently added item is the first one removed. Think of a stack of plates—add to the top, remove from the top.

Core Operations

  • push(x): Add item x to the top.
  • pop(): Remove and return the top item.
  • peek() or top(): Return (without removing) the top item.
  • is_empty(): Check whether the stack has no elements.
  • size(): Number of elements in the stack.

Time complexity for push/pop/peek is typically O(1); size can be O(1) if tracked, or O(n) if computed on demand.

Implementations

Array (Dynamic Array)–Based

  • Pros: Excellent cache locality, O(1) amortized push, simple implementation.
  • Cons: May need resizing; a fixed-capacity array risks overflow.

Linked List–Based

  • Pros: Conceptually unbounded until memory is exhausted; push/pop are O(1).
  • Cons: Extra memory per node; less cache-friendly.

Underflow occurs when popping an empty stack; always check emptiness or handle exceptions.

Common Use Cases

  • Function call stack: Manages active function calls and local variables; recursion builds nested stack frames.
  • Depth-first search (DFS): Iterative DFS uses a stack to traverse graphs/trees.
  • Parsing and expression evaluation: Convert/evaluate infix/postfix; algorithms like shunting-yard use stacks.
  • Balanced parentheses: Check matching brackets with a stack.
  • Undo/redo and navigation: Back/forward operations in editors and browsers.
  • Backtracking: Systematically explore and revert choices.

Example: Minimal Stack in Python (Dynamic Array)

class Stack:
    def __init__(self):
        self._data = []

    def push(self, x):
        self._data.append(x)

    def pop(self):
        if not self._data:
            raise IndexError("pop from empty stack")
        return self._data.pop()

    def peek(self):
        if not self._data:
            raise IndexError("peek from empty stack")
        return self._data[-1]

    def is_empty(self):
        return not self._data

    def size(self):
        return len(self._data)

Example: Balanced Parentheses

def is_balanced(s):
    pairs = {')': '(', ']': '[', '}': '{'}
    st = []
    for ch in s:
        if ch in '([{':
            st.append(ch)
        elif ch in ')]}':
            if not st or st.pop() != pairs[ch]:
                return False
    return not st

# is_balanced("(a+[b*c]-{d/e})") == True
# is_balanced("(]") == False

Example: Iterative DFS with a Stack

def dfs_iterative(graph, start):
    visited = set()
    order = []
    stack = [start]
    while stack:
        node = stack.pop()
        if node in visited:
            continue
        visited.add(node)
        order.append(node)
        # Push neighbors (reverse to mimic recursive order if desired)
        for nei in reversed(graph.get(node, [])):
            if nei not in visited:
                stack.append(nei)
    return order

Call Stack vs. Stack Data Structure

The call stack in a runtime system stores stack frames for active function calls (return addresses, locals). It is an application of the stack abstraction. Deep or infinite recursion can cause a stack overflow.

Variants and Design Considerations

  • Bounded vs. unbounded: Fixed-capacity stacks may overflow; dynamic arrays grow as needed.
  • Thread safety: Concurrent stacks need synchronization (locks) or lock-free algorithms.
  • Min-stack: Maintain an auxiliary stack to support O(1) getMin().
  • Monotonic stack: Maintains increasing/decreasing order to solve range-maximum/minimum or next-greater-element problems.
  • Two stacks to make a queue: Amortized O(1) enqueue/dequeue by transferring elements between stacks.

Gotchas

  • Check for underflow before pop() or peek().
  • For array stacks, watch capacity and resizing costs (amortized O(1)).
  • Beware unbounded growth if pushes outnumber pops (memory use).
  • In recursion-heavy code, consider converting to an explicit stack to avoid call stack overflow.

Context from Referenced By

Context from Related Topics
Pop Quiz
Topic: stacks
Level: 1
True or False:

Popping from an empty stack is called underflow.

Topic: stacks
Level: 1
Multiple Choice:

In a standard stack, which operation returns the top element without removing it?

Topic: stacks
Level: 1
Fill in the Blank:

Iterative depth-first search manages the frontier of nodes using a _____.

Topic: stacks
Level: 2
True or False:

In a dynamic array–based stack, push operations run in O(1) amortized time.

Topic: stacks
Level: 2
Multiple Choice:

Which of the following tasks is commonly solved using a stack data structure?

Topic: stacks
Level: 2
Fill in the Blank:

Using two stacks to implement a queue achieves _____ amortized time for enqueue and dequeue operations.

Topic: stacks
Level: 3
True or False:

Checking whether a string of brackets is balanced using a stack runs in O(n) time for a string of length n.

Topic: stacks
Level: 3
Multiple Choice:

Which of the following is a disadvantage specific to a linked list–based stack compared to a dynamic array–based stack?

Topic: stacks
Level: 3
Fill in the Blank:

Pushing onto a full fixed-capacity array-based stack may result in _____.

Topic: stacks
Level: 4
True or False:

A monotonic stack maintains a specific increasing or decreasing order to efficiently solve problems like next greater element and range minimum/maximum.

Topic: stacks
Level: 4
Multiple Choice:

In an iterative depth-first search (DFS) that uses a stack, why might neighbors of a node be pushed onto the stack in reverse order?

Topic: stacks
Level: 4
Fill in the Blank:

In a min-stack, constant-time getMin() is achieved by maintaining an auxiliary _____.

Topic: stacks
Level: 5
True or False:

Deep recursion can cause a stack overflow in the runtime call stack.

Topic: stacks
Level: 5
Multiple Choice:

Why can converting a deep recursive algorithm to use an explicit stack help avoid a call stack overflow?

Topic: stacks
Level: 5
Fill in the Blank:

In a runtime call stack, each active function call is represented by a _____.

Next Topic
used_by
0.94

Function Call Stack
Function call stacks in language runtimes use LIFO stack behavior to manage activation records: each call pushes a frame and each return pops it, enabling recursion and structured control flow.
used_by
0.92

Depth First Search
Iterative DFS uses an explicit stack to manage the frontier; recursive DFS leverages the call stack for the same LIFO traversal behavior.
used_by
0.92

Balanced Parentheses
Checking balanced parentheses/brackets is a classic algorithm that leverages a stack to track opening symbols and validate proper nesting in linear time.
used_by
0.92

Shunting Yard Algorithm
The shunting yard algorithm uses a stack to manage operators and parentheses when converting infix expressions to postfix (RPN) or evaluating them.
used_by
0.92

Undo Redo Systems
Undo/redo features maintain action history using LIFO stacks, allowing actions to be reversed and reapplied efficiently.
used_by
0.92

Depth First Search
Depth-first search leverages a stack (explicitly or via the call stack) to control traversal and backtracking order.
used_by
0.92

Queue Via Two Stacks
A queue can be built from two stacks—one for enqueues and one for dequeues—using transfers to convert LIFO operations into overall FIFO behavior.
used_by
0.9

Expression Evaluation
Expression evaluation algorithms (e.g., infix-to-postfix via Shunting Yard and postfix/RPN evaluation) use stacks to manage operators, operands, and parentheses according to precedence and associativity.
used_by
0.9

Monotonic Stack
A monotonic stack is a specialized usage of a stack that enforces increasing or decreasing order to efficiently solve problems like Next Greater Element, stock span, and largest rectangle in histogram.
used_by
0.88

Backtracking
Backtracking algorithms use a LIFO stack to record choices and efficiently undo steps by popping states when a path fails.