Stack
easy 14 minA stack is a linear data structure where items are added and removed at the same end, the top.
See it run
Every stack operation step by step, then the same stack running browser history, undo, the call stack and an overflow.
Operations
Push
Add an element to the top of the stack. The new element becomes the new TOP.
Step 1 of 4
The stack before
- A
- B
- CTOP
The stack holds [A, B, C] and TOP points to C. We want to run push('D').
Step 1: The stack before
def push(self, item): self.items.append(item) # new item becomes the top, O(1) amortised- Time
- O(1)
- Space
- O(1)
- vs linked list
- O(1) insert at head
- vs array insert at front
- O(n) shift
Push is always O(1): it adds to the end of the list, which is the top. No traversal and no shifting.
In the real world
The same stack doing real jobs. Pick one and step through it.
A spring-loaded plate dispenser in a restaurant kitchen: plates go on and come off only at the top.
Step 1 of 9
The stack of plates

In a busy kitchen, clean plates sit in a spring-loaded dispenser. A waiter can take only the top plate; pulling from the middle or bottom would send the pile crashing. A stack works the same way: Last In, First Out. Adding a plate is a push and taking one is a pop. Undo buttons, back buttons and function calls all work this way.
Step 1: The stack of plates
plates = []plates.append("Blue") # pushplates.append("Green") # pushplates.append("Yellow") # pushplates.append("Red") # pushtop = plates[-1] # peek -> "Red"plates.pop() # pop -> "Red"plates.pop() # pop -> "Yellow"Common mistakes
The bugs interviewers watch for, with the fix beside each.
Popping or peeking without checking for empty
criticalpop() or peek() on an empty stack is a stack underflow: Python raises IndexError, Java throws EmptyStackException and C gives undefined behaviour. It is the most common stack bug in interviews.
Wrongdef last_item(stack): return stack.pop() # IndexError when stack is emptyRightdef last_item(stack): if not stack: # check first return None return stack.pop()Recursion with no reachable base case
criticalEvery recursive call pushes a frame on the call stack. Without a base case the frames never pop and the program dies with RecursionError or a stack overflow.
Wrongdef countdown(n): print(n) countdown(n - 1) # never stopsRightdef countdown(n): if n < 0: # base case return print(n) countdown(n - 1)Pushing and popping at the front of a list
majorinsert(0, x) and pop(0) shift every other element, so each operation is O(n). The top of a list-backed stack must be the end of the list, where append and pop are O(1).
Wrongstack.insert(0, item) # O(n) shifttop = stack.pop(0) # O(n) shiftRightstack.append(item) # O(1)top = stack.pop() # O(1)Confusing a stack with a queue
majorA stack is LIFO (plates: the newest comes out first). A queue is FIFO (a line: the oldest comes out first). Using the wrong one reverses the order you process items in, for example turning BFS into DFS.
Wrongfrom collections import dequeq = deque([1, 2, 3])first = q.pop() # 3: that is stack behaviour, not FIFORightfrom collections import dequeq = deque([1, 2, 3])first = q.popleft() # 1: FIFO for a queuestack = [1, 2, 3]top = stack.pop() # 3: LIFO for a stackReaching into the middle by index
minorA stack's contract is that only the TOP is accessible. Reading stack[0] or stacki breaks the abstraction and usually signals the wrong data structure for the problem.
Wrongbottom = stack[0] # not a stack operationsecond = stack[-2]Righttop = stack[-1] # peek: the only element you may read# need random access? use a plain list, not a stackPushing onto a fixed-size stack without a full check
majorA bounded stack (a fixed array, an embedded system, a capped undo history) overflows if you push past its capacity. Check is_full() before push, just as you check is_empty() before pop.
Wrongdef push(self, item): self.items.append(item) # ignores max_sizeRightdef push(self, item): if len(self.items) >= self.max_size: raise OverflowError("stack is full") self.items.append(item)Forgetting edge cases
minorStack solutions often pass the main example and fail on an empty input, a single element, or input left over on the stack at the end (for example an unclosed bracket). Test empty, one element and many elements.
Wrongdef is_balanced(s): stack = [] for ch in s: if ch == "(": stack.append(ch) else: stack.pop() return True # misses "((" and crashes on ")"Rightdef is_balanced(s): stack = [] for ch in s: if ch == "(": stack.append(ch) elif not stack: return False else: stack.pop() return not stack # leftovers mean unbalanced
Interview tips
How to explain it
- A stack is a linear data structure that follows LIFO, Last In, First Out, like a stack of plates: you only add to or remove from the top.
- The core operations are push (add to top), pop (remove from top) and peek (view top). All are O(1).
- It can be backed by a dynamic array (push and pop at the end) or a linked list (insert and remove at the head).
- Overflow is pushing too much, past capacity or through infinite recursion. Underflow is popping from empty. Check is_full() before push and is_empty() before pop.
When to reach for a stack
- You need LIFO order: the most recent item is handled first.
- Matching brackets, evaluating expressions, parsing.
- Depth-first search, backtracking (maze, N-Queens) and turning recursion into iteration.
- Undo and redo, browser back and forward, function call management.
- Monotonic stack problems: next greater element, daily temperatures, largest rectangle in a histogram.
Memory tricks
- LIFO: Last In, First Out. The last item you put in is the first you take out.
- Pancakes: you always eat the top one first.
- Rhyme: "Stack it high, grab from the sky, last to arrive is first to say goodbye."
- Picture a vertical tower: you can only reach the top, and to reach lower items you must remove everything above.
- Overflow = Over capacity or Over recursion, a glass of water spilling over the top. Underflow = Under zero elements, sucking air from an empty cup.
Prevention checklist
- Before push: is the stack full? For a fixed size, compare against max capacity. For recursion, is there a valid base case?
- Before pop or peek: is the stack empty? Check is_empty() first, every time.
- Track size to avoid off-by-one errors, and test empty, single-element and many-element inputs.
- Do not use a stack when you need random access, FIFO order (use a queue), frequent search, access at both ends (use a deque) or BFS.