Skip to main content
Quick Reference

Stack Cheatsheet

A stack on one page — push, pop, and peek, and the traps around the bottom, empty pops, and bracket order.

10 sections 10 tables 14 code snippets

Last in, first out

Push

stack.append(3)

Pop

stack.pop()

The rule

IdeaMeaning
LIFOThe last value pushed is the first value popped
TopThe end you push onto and pop from
BottomThe first value pushed. It comes out last
Underflowpop or peek when the stack is empty
Overflowpush when a fixed stack is already full
ReversePopping everything yields the pushes in reverse order

This page is a stack. A queue is left out.

Operations

Peek leaves the top in place

top = stack[-1]

Cost at the top

OpCost
pushO(1) when it adds at the top
popO(1) when it removes the top
peekO(1). The top stays
Bottom insertO(n) on an array, because the other values shift
SearchO(n). A stack has no random access
SpaceO(n) values. A Python list append is O(1) amortized, because a resize sometimes copies

Array and links

Empty array stack

# top starts at -1

Where the top lives

BuildTop
Fixed arraytop is the last filled index. Empty means top == -1
PushIf top == capacity - 1, overflow. Else top += 1 and store there
PopIf top == -1, underflow. Else read data[top], then top -= 1
LeftoverThe old value can still sit in the cell. The logical stack ends at top
Linked headThe head is the top. Push and pop at the head are O(1)
Linked tailPopping the tail of a singly linked list is O(n)

A Python list

The slow end

# stack.pop(0) takes the bottom

Nothing to pop

# stack.pop() on an empty list raises IndexError

The list is the stack

CallMeaning
append(x)Push onto the end
pop()Pop the end. pop(0) removes the bottom and is O(n)
stack[-1]Peek. An empty list raises IndexError
if stackAn empty list is false. A new [] is empty, and it is not None
dequeappend and pop at the right end are O(1). A list is the usual stack
LifoQueueA thread-safe stack. get() waits when empty. get_nowait() raises queue.Empty

Brackets

The closer must match the top

if not stack or stack[-1] != pair[ch]:
    return False
stack.pop()

Counts are not order

# ([)] is the wrong order

One pass

CaseResult
()[]{}Openers are popped by their closers. The stack ends empty. Balanced
([)]The counts can match. The closer does not match the top. Unbalanced
(()An opener is left. Unbalanced
)A closer arrives while the stack is empty. Unbalanced
LettersA bracket checker can skip them. An expression checker has to handle them
CostEach bracket is pushed once or popped once. O(n) time

The call stack

Each call waits on a deeper one

def fact(n):
    if n == 0:
        return 1
    return n * fact(n - 1)

Frames

PieceMeaning
FrameOne call. It holds the parameters, the locals, and where to return
CallPushes a frame. Return pops it
fact(3)Frames for 3, 2, 1, then 0. The base case starts the pops
LimitCPython starts at 1000 frames. Past that, RecursionError
Tail callCPython keeps the current frame. A tail call still uses a new one
The listThe frame stores a reference. The list object lives on the heap

Min stack

Remember this minimum

if not mins or x <= mins[-1]:
    mins.append(x)

O(1) minimum

StepRule
PushPush x on the values. Also push it on mins when mins is empty or x <= the min top
PopPop the value. When it equals the min top, pop mins too
getMinThe top of mins. O(1)
DuplicatesUse <=. A strict < forgets the second copy of the same minimum
One variableA lone min cannot bring back the previous min after that value is popped
SpaceO(n) extra when every push is a new minimum

Next greater

Pop anything smaller

while stack and stack[-1] < x:
    stack.pop()

One decreasing stack

PieceMeaning
OrderFrom bottom to top the values stay decreasing
New xWhile the top is < x, pop it. x is the next greater for each popped value
Then pushx goes on the stack for a later, larger value
Left overA value still on the stack has no next greater to its right
EqualsA strict < leaves an equal top in place. Next greater means strictly greater
CostEach value is pushed once and popped at most once. O(n)

Where stacks show up

Operand order

# postfix: the first pop is the right operand

The same LIFO idea

JobHow the stack helps
UndoEach action is pushed. Undo pops the latest one
BackEach page is pushed. Back pops
PostfixPush numbers. An operator pops two, applies, and pushes the result
3 4 -Pop 4, then pop 3. The result is 3 - 4, because the first pop is the right operand
DFSAn explicit stack holds the next nodes. Recursion uses the call stack for the same walk
InfixA new operator pops any waiting operator of higher or equal precedence, then the new one waits

Interview traps

Peek is not a remove

# stack[-1] peeks. pop() removes

Index 0 is the oldest

# stack[0] is the bottom

Traps worth memorising

TrapWhat happensPrefer
pop(0) or insert(0, x)Touches the bottom, and the shift is O(n)append and pop()
Peek, then assume it is goneThe top is still therepop() when the value should leave
stack[0]The oldest value, the bottomstack[-1] for the top
Empty pop or peekIndexError on a list. Underflow on a fixed arrayTest the stack first
Equal bracket counts([)] can count as balanced and still be illegalMatch the top opener, then require an empty stack
No base caseFrames pile up until RecursionErrorA return that stops the recursion

How to use this page: push with append, read the top with [-1], and pop from that same end.