๐ Introduction
Stacks and queues are two of the most fundamental data structures in computer science.
They are the backbone of:
Expression evaluation (infix, postfix)
Backtracking algorithms
Tree and graph traversals
Task scheduling and async operations
In this post, weโll cover:
โ What stacks and queues are
โ Pythonic implementations using list and collections.deque
โ Real-world problems and patterns
โ Best practices and interview tips
๐ฆ 1๏ธโฃ What is a Stack? (LIFO โ Last In, First Out)
Think of a stack of plates โ you can only remove or add from the top.
๐น Basic Operations:
- push: Add to top - pop: Remove from top - peek: See top item - is_empty: Check if empty
๐น Python Implementation:
stack = [] stack.append(1) # push stack.append(2) print(stack.pop()) # 2 print(stack[-1]) # peek โ 1
โ Pythonโs list provides all you need for stack operations.
๐ Real-World Stack Use Cases
- Undo/Redo systems - Backtracking (maze, Sudoku) - Balanced parentheses checking - Function call stack (recursion)
๐ Example: Valid Parentheses
def is_valid_parentheses(s): stack = [] mapping = {')': '(', ']': '[', '}': '{'} for char in s: if char in mapping.values(): stack.append(char) elif char in mapping: if not stack or stack.pop() != mapping[char]: return False return not stack
๐ฆ 2๏ธโฃ What is a Queue? (FIFO โ First In, First Out)
Think of a line at the bank โ the first person in is the first one served.
๐น Basic Operations:
- enqueue: Add to rear - dequeue: Remove from front - peek: View front item
๐น Python Implementation with deque:
from collections import deque queue = deque() queue.append(1) # enqueue queue.append(2) print(queue.popleft()) # dequeue โ 1
โ deque is preferred for performance: O(1) operations from both ends.
๐งญ Real-World Queue Use Cases
- Breadth-first search (BFS) in trees and graphs - Task scheduling (OS, threads, async) - Buffering data streams - Print job queues
๐ Example: BFS in a Binary Tree
from collections import deque def bfs(root): if not root: return queue = deque([root]) while queue: node = queue.popleft() print(node.val) if node.left: queue.append(node.left) if node.right: queue.append(node.right)
๐งช 3๏ธโฃ Interview-Favorite Problems
Problem | Data Structure | Pattern |
---|---|---|
Valid Parentheses | Stack | Matching pairs |
Min Stack | Stack | Track min values |
Daily Temperatures | Stack | Monotonic stack |
BFS Traversal | Queue | Level-order |
Rotten Oranges | Queue | BFS in grid |
Design Circular Queue | Queue | Array + Pointers |
๐ง 4๏ธโฃ Implementing a Min Stack
class MinStack: def __init__(self): self.stack = [] self.min_stack = [] def push(self, val): self.stack.append(val) min_val = val if not self.min_stack else min(val, self.min_stack[-1]) self.min_stack.append(min_val) def pop(self): self.stack.pop() self.min_stack.pop() def top(self): return self.stack[-1] def get_min(self): return self.min_stack[-1]
โ All operations in O(1) time.
โ Best Practices
โ๏ธ Use deque for queues and double-ended operations
โ๏ธ Donโt use list.pop(0) for queues โ itโs O(n)
โ๏ธ Know stack vs queue behavior clearly โ it affects algorithm choice
โ๏ธ Watch out for edge cases: empty stack/queue, null root, etc.
โ๏ธ Practice problems with state tracking and multi-level logic (e.g., BFS + levels)
๐ง Summary
โ๏ธ Stacks (LIFO) and queues (FIFO) solve real-world ordering and traversal problems
โ๏ธ Python provides clean abstractions using list and deque
โ๏ธ Learn core patterns like parentheses validation, BFS, and monotonic stacks
โ๏ธ Mastering these unlocks tree/graph algorithms and many classic interview questions
๐ Coming Up Next:
๐ Part 4: Hash Maps and Sets โ Frequency Maps, Lookups, and Real-World Applications
Weโll cover:
1. Counter, defaultdict, set Grouping anagrams
Sliding window with hash map
Interview favorites: 2-sum, longest substring, etc.
Top comments (0)