Stack and queue data structures from basic principles to production design
Master LIFO and FIFO fundamentals, implement robust stacks and queues with error handling, and explore real-world buffer architectures.
MonksBit Desk
November 18, 2026 · 8 min read · 80 views
Read
A stack is a linear collection governed by the Last-In, First-Out principle, where items are inserted and removed exclusively from one boundary called the top. A queue is a linear collection governed by the First-In, First-Out principle, where items are inserted at one boundary called the rear and removed from the opposite boundary called the front.
You will need. Basic knowledge of variables and functions in Python · Understanding of arrays and list indexing
The full lesson
Level 1 · Beginner: Understanding Last-In, First-Out and First-In, First-Out mechanics
Stacks and queues govern the order in which data is processed. Why they matter is simple: they restrict arbitrary access to data, guaranteeing predictable sequencing. A stack ensures that the most recent task is handled first, making it indispensable for undo actions, parsing nested expressions, and tracking function calls. A queue guarantees fairness by processing events in arrival order, forming the foundation of task scheduling, packet buffering, and asynchronous message delivery.
Consider a small manual walk-through for a stack. We start with an empty collection. We push the number 10, so the stack holds [10]. We push 20, making the stack [10, 20], where 20 is at the top. When we pop, we remove and return the top item, which is 20, leaving [10]. Pushing 30 yields [10, 30]. The last element inserted is always the first one ejected.
Now consider the same sequence for a queue. We start empty. We enqueue 10, resulting in [10]. We enqueue 20, resulting in [10, 20], where 10 is the front and 20 is the rear. When we dequeue, we take from the front, returning 10 and leaving [20]. If we enqueue 30, the queue becomes [20, 30]. The earliest arrival is always the first one serviced.
In standard Python, a list can demonstrate stack operations using append to push and pop without arguments to pop. For a queue, collections.deque provides an append operation to enqueue and popleft to dequeue efficiently.
Minimal demonstrations of stack and queue using built-in Python primitives
from collections import deque# Stack demonstration using Python liststack = []stack.append(10) # pushstack.append(20) # pushtop_item = stack.pop() # returns 20# Queue demonstration using collections.dequequeue = deque()queue.append(10) # enqueuequeue.append(20) # enqueuefront_item = queue.popleft() # returns 10print("Stack top removed:", top_item)print("Queue front removed:", front_item)
Key takeaways
- Stacks follow Last-In, First-Out (LIFO); the latest element added is the first one removed.
- Queues follow First-In, First-Out (FIFO); the oldest element added is the first one removed.
- Restricting access to only the boundaries guarantees predictable ordering and simpler debugging.
Level 2 · Intermediate: Encapsulated implementations with boundary protection and testing
Using raw lists directly across a codebase invites bugs because nothing stops external code from mutating or reading arbitrary indices. Production-ready code wraps underlying storage in dedicated classes that expose only explicit operations: push, pop, and peek for a stack; enqueue, dequeue, and peek for a queue. Custom error types must be raised when an operation is performed on an empty structure.
For queue implementations, using a dynamic array or list with index 0 removal takes linear time because every remaining element shifts left by one slot. To achieve constant time for queue operations, we use a doubly linked node list or Python collections.deque, which tracks pointers to both ends directly.
To verify these classes, testing must evaluate normal sequential modifications, alternating insertions and removals, single-element boundary states, and the exact exceptions raised when attempting to pop or dequeue an empty container.
Complete encapsulated Stack and Queue classes with boundary error handling
from collections import dequefrom typing import Anyclass EmptyStructureError(IndexError): """Raised when accessing elements from an empty container.""" passclass Stack: def __init__(self) -> None: self._items: list[Any] = [] def push(self, item: Any) -> None: self._items.append(item) def pop(self) -> Any: if not self._items: raise EmptyStructureError("Cannot pop from an empty stack.") return self._items.pop() def peek(self) -> Any: if not self._items: raise EmptyStructureError("Cannot peek into an empty stack.") return self._items[-1] def is_empty(self) -> bool: return len(self._items) == 0 def __len__(self) -> int: return len(self._items)class Queue: def __init__(self) -> None: self._items: deque[Any] = deque() def enqueue(self, item: Any) -> None: self._items.append(item) def dequeue(self) -> Any: if not self._items: raise EmptyStructureError("Cannot dequeue from an empty queue.") return self._items.popleft() def peek(self) -> Any: if not self._items: raise EmptyStructureError("Cannot peek into an empty queue.") return self._items[0] def is_empty(self) -> bool: return len(self._items) == 0 def __len__(self) -> int: return len(self._items)# Validations = Stack()s.push("task_1")s.push("task_2")assert s.peek() == "task_2"assert s.pop() == "task_2"assert s.pop() == "task_1"assert s.is_empty()q = Queue()q.enqueue("request_a")q.enqueue("request_b")assert q.peek() == "request_a"assert q.dequeue() == "request_a"assert q.dequeue() == "request_b"assert q.is_empty()
Key takeaways
- Encapsulation hides backing data storage and enforces operation invariants.
- Popping or peeking from an empty container must fail deliberately via custom exceptions.
- Dequeuing by shifting array elements introduces O(N) penalties; use pointer-linked nodes or deques for O(1) performance.
Level 3 · Advanced: Fixed-capacity circular buffers, monotonicity, and system trade-offs
In high-throughput systems such as network drivers, operating system kernels, and audio processing pipelines, dynamic memory allocation during enqueueing is unacceptable. Dynamic allocation creates memory fragmentation and unpredictable latency spikes from reallocation. These systems use a fixed-capacity circular buffer, where a static array uses modular arithmetic to wrap front and rear indices around when they hit the array limit.
Stacks also appear as algorithmic acceleration tools. A monotonic stack is a specialized stack that maintains elements in strictly increasing or decreasing order. By discarding elements that violate this order before inserting a new element, monotonic stacks solve problems like the Next Greater Element or largest rectangle in a histogram in linear total time.
Trade-offs exist between queues and priority queues. A standard queue guarantees starvation freedom through FIFO ordering, but cannot prioritize urgent tasks. A circular buffer achieves zero-allocation deterministic latency, but drops packets or blocks callers if producer threads outpace consumer threads.
Fixed-capacity circular buffer queue with zero dynamic allocations after initialization
from typing import Any, Optionalclass CircularQueue: def __init__(self, capacity: int) -> None: if capacity <= 0: raise ValueError("Capacity must be strictly positive.") self._capacity = capacity self._buffer: list[Optional[Any]] = [None] * capacity self._head = 0 self._tail = 0 self._size = 0 def enqueue(self, item: Any) -> bool: if self.is_full(): return False self._buffer[self._tail] = item self._tail = (self._tail + 1) % self._capacity self._size += 1 return True def dequeue(self) -> Any: if self.is_empty(): raise IndexError("Queue is empty.") item = self._buffer[self._head] self._buffer[self._head] = None self._head = (self._head + 1) % self._capacity self._size -= 1 return item def is_full(self) -> bool: return self._size == self._capacity def is_empty(self) -> bool: return self._size == 0 def __len__(self) -> int: return self._sizering = CircularQueue(capacity=2)assert ring.enqueue("packet_1") is Trueassert ring.enqueue("packet_2") is Trueassert ring.enqueue("packet_3") is False # Rejected because buffer is fullassert ring.dequeue() == "packet_1"assert ring.enqueue("packet_3") is True # Wrapped around safelyassert ring.dequeue() == "packet_2"assert ring.dequeue() == "packet_3"
Key takeaways
- Circular buffers eliminate reallocation overhead and guarantee fixed O(1) latency using modulo arithmetic.
- Monotonic stacks maintain an invariant of sorted order to reduce quadratic nested searches down to O(N).
- Fixed buffers force an architectural choice when full: block, overwrite the oldest item, or reject new entries.
Complexity
- Time: O(1) for push, pop, enqueue, and dequeue; O(1) best and worst case with circular buffers or deques.
- Space: O(N) where N is the number of items stored in the structure.
Adding or removing elements at designated ends involves pointer adjustments or fixed-offset writes with no scanning required, yielding constant O(1) time. Space scales linearly with the number of stored elements.
Common mistakes
- Using a standard Python list as a queue and calling pop(0), which causes O(N) element shifts on every removal.
- Failing to check for empty collections before invoking peek or pop, causing unhandled runtime errors.
- Confusing LIFO and FIFO behavior when implementing backtracking algorithms, leading to infinite loops or incorrect search order.
- Omitting modulo wrapping logic when advancing pointers in circular buffer implementations.
Practice problems
- Balanced Parentheses Validator (easy). Hint: Iterate through characters; push opening brackets onto a stack and verify that closing brackets match the popped element.
- Implement a Queue Using Stacks (medium). Hint: Use two separate stacks: push new elements onto an intake stack, and only transfer them to an output stack when the output stack is empty.
- Next Greater Element via Monotonic Stack (hard). Hint: Traverse the array while keeping a stack of unfulfilled element indices in strictly decreasing value order.
Summary
Stacks and queues provide strict, predictable constraints for handling data in LIFO and FIFO sequences. Choosing between dynamic linked representations and fixed circular buffers dictates how memory allocation and latency behave in real systems.
Was this helpful?
Comments (0)
Sign in or create an account to join the conversation.
- No comments yet. Be the first!