Stack

DSA · Stacks and Queues

Theory

A stack is a Last-In-First-Out (LIFO) collection: the last item pushed is the first one popped, like a pile of plates. It supports push (add to top), pop (remove from top) and peek (look at the top), all in O(1). In Python a list works as a stack using append() and pop(). The function call stack that runs your programs is itself a stack.

Why we use it

Stacks naturally handle anything that must be undone or matched in reverse order.

When to use it

Use a stack for undo/redo, matching brackets, evaluating expressions, browser back navigation, DFS, and backtracking.

How it works

  1. Empty stack
  2. Push? Yes: Add item on top. No: Pop: remove the top item.
  3. Stack empty when popping? Yes: Underflow error. No: Return the popped item.
  4. LIFO: last in, first out

Syntax

stack = []
stack.append(x)   # push   O(1)
stack.pop()       # pop    O(1)
stack[-1]         # peek   O(1)
not stack         # is empty

Example

def is_balanced(expr):
    pairs = {")": "(", "]": "[", "}": "{"}
    stack = []
    for ch in expr:
        if ch in "([{":
            stack.append(ch)
        elif ch in pairs:
            if not stack or stack.pop() != pairs[ch]:
                return False
    return len(stack) == 0

for e in ["(a+b)*[c-d]", "{[}]", "((x)"]:
    print(e, "balanced:", is_balanced(e))

undo = []
for action in ["type A", "type B", "bold"]:
    undo.append(action)
print("Undo last:", undo.pop(), "| remaining:", undo)

Key points

DSA topics

Introduction to DSA

Arrays and Searching

Sorting Algorithms

Linked Lists

Stacks and Queues

Hashing

Trees

Heaps

Graphs

Algorithm Techniques

Classic Algorithms

Dynamic Programming

T
Tech Town
Log InSign Up Free
Home SQL Python DSA Power BI Snowflake Databricks Spark Gen AI Practice Problems Contest Blog

Data Structures & Algorithms

The complete DSA roadmap: theory, why and when to use every structure and algorithm, Big O complexity, and Python code you can run right here in the browser.

{{ sectionCount }}
Sections
{{ topicCount }}
Topics
Free
Forever
Hands-on practice Practice DSA Online 251 problems across 13 patterns, with hidden tests and step-by-step optimal solutions. Start practising →
Section {{ sec.num }}

{{ sec.label }}

DSA  /  {{ current.sectionLabel }}  /  {{ current.name }}

{{ current.name }}

Theory

{{ current.def }}

Why we use it

{{ current.why }}

When to use it

{{ current.when }}

Flowchart — how {{ current.name }} works
{{ nd.text }}
{{ nd.text }}
◇ {{ nd.text }}
Yes → {{ nd.yes }}
No → {{ nd.no }}
Step-by-step visualisation
{{ cell.v }}
{{ cell.i }} {{ cell.tag }}
Step {{ vizStepLabel }}: {{ vizNote }}
■ comparing ■ swapping / moving ■ done / found ■ out of range
Complexity & Pseudocode
{{ current.syntax }}
Example Code
{{ current.example }}
▶ Try It Live — runs real Python 3 in your browser (first run loads the engine)
{{ liveOutput }}
{{ liveError }}
Key Points — click to check off as you learn
  • {{ pt.mark }} {{ pt.text }}

Share this topic