Stacks & Queues
Data Structures & Algorithms · Linked Lists, Stacks & Queues · Intermediate · 12 min
Last-in-first-out vs first-in-first-out, and when each saves you.
A spring-loaded plate dispenser next to a coffee-shop line. Letters drop onto the plate pile; every # lifts the top plate off. The line, meanwhile, always serves whoever has waited longest.
The idea in everyday words
A stack is a pile of plates: you put a plate on top and take from the top (Last In, First Out). A queue is a line at a coffee shop: first person in line gets served first (First In, First Out).
Stack (LIFO)
push(x)puts on top,pop()removes the top. Both O(1).- Used for: undo button, browser back button, matching brackets, recursion.
Queue (FIFO)
enqueue(x)joins the back,dequeue()leaves the front.- Used for: printers, task schedulers, BFS in graphs, message queues in system design.
Classic: Valid Parentheses
Is "({[]})" balanced? Push every opener. On a closer, the top of the stack MUST be its matching opener: pop it. At the end the stack must be empty.
Step by step
- Read '(':
Opener → push. Stack: (
- Read '[':
Opener → push. Stack: ( [
- Read ']':
Top is '[' ✅ match → pop. Stack: (
- Read ')':
Top is '(' ✅ match → pop. Stack empty.
- End:
Stack empty → balanced = true.
Code example
def is_valid(s):
pairs = {")": "(", "]": "[", "}": "{"}
stack = []
for ch in s:
if ch in "([{":
stack.append(ch)
elif not stack or stack.pop() != pairs[ch]:
return False
return len(stack) == 0
print(is_valid("({[]})"), is_valid("(]"))Complexity
- Time: O(n)
- Space: O(n)
Interview tips
Valid Parentheses is a top-10 question.
'Next greater element' problems use a monotonic stack.
In Python use collections.deque for an O(1) queue.
Challenge: Undo the Typing
You get a string where # means backspace. Return the final text.
Example: apply_backspaces("ab#c") → "ac". Use a stack!
Solve it in the browser with tests, hints and an AI coach.
Practice problems
- Valid Parentheses (Easy)
- Backspace String Compare (Easy)
- Implement Queue using Stacks (Easy)
- Min Stack (Medium)
More in Linked Lists, Stacks & Queues
Previous: Linked Lists · Next: Deques & Monotonic Stacks