What is a Stack?
Data Structures·5 min·Python code
Stacks store items in last in, first out (LIFO) order, so the newest element leaves first. Push, pop and peek all cost O(1) time.
How a Stack Stores Items in LIFO Order
Picture a stack of plates. You add a plate to the top, and when you need one, you take it from the top. You cannot pull a plate from the middle without lifting everything above it.
That is LIFO. Last item you put in is the first item you get back.
One rule makes stacks useful. Whenever the most recent thing must be handled first, like matching brackets, undoing edits or tracking which function called which, you get that order for free.
Stack Operations and Underflow Handling
Three operations cover the work. Push adds an element to the top, pop removes and returns the top element and peek shows the top without removing it. Most implementations add isEmpty and size.
All the action happens at one end, so every operation costs O(1). Nothing shifts and nothing searches.
Under the hood, a stack wraps a dynamic array, like a Python list, or a singly linked list. Arrays push and pop at the tail, while linked lists add and remove at the head.
Guard against popping an empty stack, called stack underflow. Raise an error instead of failing silently.
Where LIFO Order Solves Problems
Four patterns cover most problems here. Balanced parentheses checking pushes every opening bracket and pops when it meets a closing one, then verifies the pair matches.
Monotonic stacks keep elements in sorted order to answer next greater element questions in O(n) time.
Depth-First Search and recursion lean on a stack, either explicit or the language's call stack, to remember where to backtrack. Undo and redo in an editor use two stacks of past states.
Practise all four on CodeStory's stack practice problems.
Stack Code Example in Python
class Stack:
def __init__(self):
self._items = []
def push(self, item):
self._items.append(item) # add to top, O(1)
def pop(self):
if not self._items:
raise IndexError("pop from empty stack")
return self._items.pop() # remove top, O(1)
def peek(self):
if not self._items:
raise IndexError("peek from empty stack")
return self._items[-1] # show top, no removal
def is_empty(self):
return not self._items
def __len__(self):
return len(self._items)
Edit this code in the browser IDE on CodeStory, free on the platform. Open the CodeStory App
Stack Time and Space Complexity
| Time | O(1) for push, pop, peek, isEmpty and size |
|---|---|
| Space | O(n) for n stored elements |
Array backed push and pop cost amortised O(1), because an occasional resize costs O(n) but averages out over many operations. Linked list backings give true worst case O(1) per operation, with one extra pointer per node.
Watch a Stack Step by Step
Seeing items push on and pop off your own input shows the LIFO order at work. Follow either of these one step at a time.
When to Use a Stack
- Validating nested structure like parentheses, brackets, HTML or XML tags and JSON.
- Reversing a sequence or processing items in the opposite order they arrived.
- Implementing depth first search or converting a recursive algorithm into an iterative one.
- Solving next greater element, next smaller element and histogram problems with a monotonic stack.
Mistakes to Avoid
- Popping or peeking without checking for an empty stack, which triggers an underflow error or an out of bounds access.
- Reaching into the middle. If you index elements other than the top, that structure is the wrong tool, so choose an array, deque or heap.
- Working on the slow end. Pushing or popping at the front of a dynamic array costs O(n), so always work on the end that gives O(1).
Stack FAQs
Is a stack hard to learn?
No. Stacks follow one rule, LIFO, and three operations, push, pop and peek. Recognising when a problem calls for a stack is the harder part, and practice on balanced brackets and monotonic stacks builds it.
What is the time complexity of stack operations?
Push, pop, peek, isEmpty and size all cost O(1). Array backed stacks make push and pop amortised O(1), because occasional resizing costs O(n) but averages out. Space is O(n) for n stored elements.
What is the difference between a stack and a queue?
Stacks are LIFO, so the last item in is the first out and both add and remove happen at one end. Queues are FIFO, so you add at one end and remove from the other. Use LIFO to reverse or backtrack and a queue to process items in arrival order, like breadth-first search.
When should I use a stack instead of a plain array?
Choose LIFO storage when access is strictly last in, first out and you touch only the top. Naming it a stack makes that intent obvious and blocks accidental middle access. Use an array or deque when you need random access or both ends.
What is stack underflow?
Stack underflow happens when you pop or peek an empty stack. Check isEmpty first or raise an error, so the bug shows up instead of staying hidden.
How do you check balanced parentheses with a stack?
Push every opening bracket. When you meet a closing bracket, pop the top and check that the pair matches. Strings are balanced if every pair matches and the stack ends empty.
How do I practise stacks on CodeStory?
Follow valid parentheses and next greater element in the visualisers, then try CodeStory's stack practice problems on your own.
Related Guides
Guides are step one. In a CodeStory batch you build the stack yourself, then explain every push and pop in a scored mock round.
Talk to a Mentor