Menu
Coddy logo textTech

Stack

Last updated

A stack is a collection with exactly one open end. You add a value by pushing it onto the top, and you remove one by popping the top back off, so the last value in is always the first one out. That is what LIFO means, and it is the entire rule: there is no way to reach into the middle without removing what sits above it first. Press Play above and watch the column grow with each push and shrink from the same end with each pop.

The restriction is the point. Because both operations touch only the top, each one is O(1) no matter how tall the stack gets, and that predictability is why stacks sit under so much of computing: the call stack that runs recursion, undo history in an editor, bracket matching in a parser, and the explicit stack that turns a recursive depth-first search into a loop. Swap the removal end and you get a queue instead.

Time & space complexity

For the standard array-backed or linked-list-backed stack:

OperationComplexityNotes
PushO(1)Amortized O(1) on a dynamic array, which occasionally resizes.
PopO(1)Always the top element, so no shifting is needed.
Peek (top)O(1)Read the top without removing it.
SearchO(n)Not what a stack is for: you must pop your way down.
SpaceO(n)One slot per stored value.

Step by step

StepWhat happens
1The stack starts empty, with the top pointing at nothing.
2Push writes the value at the top position and moves the top up by one.
3Each further push lands directly above the previous value.
4Pop reads the value at the top, then moves the top down by one.
5The value that comes back is always the most recently pushed one.
6Popping an empty stack is an error, called a stack underflow, so real code checks is_empty() first.

Worked example

Pushing 3, 7, 5 and then draining the stack:

OperationStack (bottom to top)Returns
push(3)[3]nothing
push(7)[3, 7]nothing
push(5)[3, 7, 5]nothing
pop()[3, 7]5, the newest value
pop()[3]7
pop()[]3, the oldest value, last

When to use a stack

Use it whenAvoid it when
You need the most recent item back first: undo, back buttons, bracket matchingYou need the oldest item first, which is a queue
You are turning a recursive algorithm into an iterative oneYou need to search or index into the middle of the data
You are parsing nested structure such as expressions, JSON, or HTMLMany readers need arbitrary access, where an array or map fits better
You want guaranteed O(1) insertion and removal with no rebalancingYou need the data kept in sorted order, which a heap or tree gives you

Stack code

A clean, runnable Stack implementation in Python, JavaScript, Java, C++, C. Pick a language, copy the code, or open it pre-loaded in the Coddy Playground.

Stack code in Python

Python
1stack = []2
3# Push three values onto the top4for value in [3, 7, 5]:5    stack.append(value)6    print(f"push {value} -> {stack}")7
8# Pop them back off: last in, first out9while stack:10    value = stack.pop()11    print(f"pop  {value} -> {stack}")12
13print("empty:", len(stack) == 0)
Run this code in the Python Playground

Stack FAQ

What does LIFO mean?
Last in, first out: the most recently pushed value is the first one popped. A pile of plates is the usual picture, you take the plate you just put down, not the one at the bottom. A queue is the opposite discipline, FIFO.
What is the difference between a stack and a queue?
Only which end you remove from. Both add at one end in O(1); a stack removes from that same end (LIFO), a queue removes from the other end (FIFO). Everything else, including the complexity table above, is identical.
What are the main stack operations?
push adds a value on top, pop removes and returns the top value, peek (sometimes top) reads the top without removing it, and is_empty reports whether anything is left. All four are O(1).
What is a stack overflow?
Pushing onto a stack that has no room left. The famous case is the call stack: every function call pushes a frame, so a recursion that never reaches its base case keeps pushing until the runtime's stack limit is hit and the program crashes. The mirror error, popping an empty stack, is a stack underflow.
How is a stack implemented?
Two common ways. A dynamic array pushes and pops at the end, which is O(1) amortized and cache-friendly: Python's list and Java's ArrayDeque work this way. A linked list pushes and pops at the head, which is worst-case O(1) with no resizing but costs a pointer per element. C++'s std::stack is an adaptor that runs on std::deque by default, a segmented array, and accepts another container if you pass one.
Where are stacks used in real programs?
The call stack for function calls and recursion, undo and redo history, browser back navigation, expression evaluation and bracket matching in parsers, and the explicit stack that converts a recursive depth-first search into an iterative loop.
Coddy programming languages illustration

Master algorithms with Coddy

GET STARTED