Build a FIFO Queue: Compare Linked List, Array, and Ring Buffer
Data Structure DesignModel answerLast updated
Implement a queue with enqueue, dequeue, peek, and isEmpty. Compare linked list, dynamic array, and circular buffer approaches.
Implement a first-in-first-out (FIFO) queue supporting these operations:
enqueue(item)– add an item to the backdequeue()– remove and return the item at the frontpeek()– return the front item without removing itisEmpty()– check if the queue contains no items
Compare three implementation strategies:
- Singly linked list with head and tail pointers
- Dynamic array with a head index to avoid shifting
- Circular buffer (ring buffer) with wraparound indexing
For each approach, analyze:
- Time complexity (worst-case and amortized) for all operations
- Space complexity and memory overhead per element
- Cache locality and practical performance characteristics
- Amortized cost of resizing operations
- Handling of edge cases: empty queue (underflow), full queue (overflow), wraparound
Discuss when you would choose each implementation in practice. Address concurrent access: compare blocking (mutex-based) versus non-blocking (lock-free) designs for single-producer-single-consumer and multi-producer-multi-consumer scenarios.
Provide a working implementation of the circular buffer approach in Python, supporting both bounded (fixed capacity) and growable (auto-resize) modes.
Hints
Hint 1
Track both head position and size explicitly to distinguish empty from full states in a ring buffer
Hint 2
Amortized analysis: doubling on growth and halving at 1/4 capacity avoids thrashing at boundaries
Hint 3
For lock-free SPSC queues, pad head and tail onto separate cache lines to prevent false sharing
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
A FIFO queue requires efficient insertion at one end and removal at the other. The challenge is maintaining O(1) operations at both ends while managing memory efficiently.
Three Implementations
1. Singly Linked List
Maintain head (front) and tail (back) pointers. Enqueue appends a new node after tail and updates tail. Dequeue removes the node at head and advances head.
- Pros: Every operation is strict O(1) worst-case. No resizing delays. Unbounded capacity.
- Cons: 16+ bytes overhead per node (pointer + allocator metadata). Poor cache locality due to pointer chasing across the heap. Frequent allocations stress the allocator and garbage collector.
2. Dynamic Array with Head Index
Use an array and track head and size. Enqueue appends at head + size. Dequeue increments head. When head grows large, compact by shifting elements back to index 0.
- Pros: Simpler than a ring buffer.
- Cons: Compaction is O(n). Memory between index 0 and
headsits unused until compaction. Less efficient than a ring buffer.
3. Circular Buffer (Ring Buffer)
Use a fixed array with head, size, and capacity. The tail position is computed as (head + size) % capacity. Indices wrap around the array boundary.
-
Bounded mode: Fixed capacity. Enqueue on a full buffer raises an error or blocks.
-
Growable mode: Double capacity when full, halve when size drops to 1/4 capacity.
-
Pros: O(1) operations for bounded mode. Amortized O(1) for growable mode. Excellent cache locality. Minimal memory overhead.
-
Cons: Growable mode has occasional O(n) resize pauses.
Why Ring Buffer Wins
The circular buffer is the standard choice for production systems. It combines the efficiency of contiguous storage with O(1) access at both ends. By tracking size explicitly, it avoids the classic "empty vs. full" ambiguity when head == tail.
Complexity Analysis
| Operation | Linked List | Dynamic Array | Circular Buffer (bounded) | Circular Buffer (growable) |
|---|---|---|---|---|
| enqueue | O(1) worst | O(1) amortized | O(1) worst | O(1) amortized |
| dequeue | O(1) worst | O(1) amortized | O(1) worst | O(1) amortized |
| peek | O(1) | O(1) | O(1) | O(1) |
| isEmpty | O(1) | O(1) | O(1) | O(1) |
| Space | O(n) | O(n) | O(n) | O(n) |
Amortized Resizing: When doubling from capacity 1 to N, you copy 1 + 2 + 4 + ... + N/2 ≈ N elements total. Spread over N enqueues, that's O(1) per operation. Shrink at 1/4 full (not 1/2) to prevent resize thrashing when operations alternate near the boundary.
Memory Overhead: Linked lists carry pointer and allocator overhead (16–50+ bytes per node in common runtimes). Arrays waste at most 2× capacity after doubling, or 4× just before shrinking. Ring buffers are far more memory-efficient in practice.
Cache Performance: Contiguous array storage enables hardware prefetching and fewer cache misses. Linked lists require one cache miss per node traversal. Benchmarks often show 5–10× speedups for ring buffers over linked lists despite identical big-O.
Edge Cases and Error Handling
- Underflow: Calling
dequeue()orpeek()on an empty queue. Raise an exception, returnNone, or return anOptionaltype. Be explicit about the contract. - Overflow: Applies to bounded queues. Common strategies:
- Reject: raise an error or return failure
- Block: wait until space is available (requires locks and condition variables)
- Overwrite: discard the oldest element (useful for streaming data where only recent values matter)
- Grow: expand capacity (turns bounded into growable)
- Wraparound: Test enqueue/dequeue sequences that cross the array boundary. Verify resizing works correctly when contents are wrapped.
- Memory leaks: Clear dequeued slots (set to
None) so garbage collectors can reclaim objects. - Invalid capacity: Reject zero or negative capacity at construction.
Concurrency Considerations
Blocking (Mutex-Based)
Protect the queue with a lock and use condition variables (not_empty, not_full). Producers wait when full; consumers wait when empty. This is straightforward and correct (Python's queue.Queue uses this model). The cost: lock contention and context switches add microsecond-scale latency.
Non-Blocking (Lock-Free)
Single-Producer Single-Consumer (SPSC):
- Use a bounded ring with power-of-two capacity for fast modulo (
index & (capacity - 1)). - Only the producer writes
tail; only the consumer writeshead. - Use atomic operations with acquire/release semantics.
- Pad
headandtailto separate cache lines (64-byte alignment) to prevent false sharing. - No locks needed. This is the pattern used in LMAX Disruptor and low-latency trading systems.
Multi-Producer Multi-Consumer (MPMC):
- Use CAS-based algorithms (e.g., Michael-Scott lock-free queue) or per-slot sequence numbers.
- Requires handling the ABA problem and safe memory reclamation (hazard pointers or epoch-based schemes).
- Operations return immediately ("full" or "empty") rather than blocking; callers must spin, back off, or drop work.
Growable buffers are difficult to make lock-free because resizing requires exclusive access. Concurrent queues are typically fixed-capacity.
When to Use Each Implementation
- Circular buffer (bounded): Known maximum size, hard real-time latency requirements, producer-consumer pipelines, or backpressure control. Default for systems programming.
- Circular buffer (growable): General-purpose single-threaded queue. Similar to Python's
collections.deque(which uses a linked list of fixed blocks). - Linked list: Unbounded capacity with guaranteed O(1) worst-case and no resize pauses. Suitable for intrusive data structures or as the foundation for lock-free MPMC queues.
- Dynamic array with head index: Quick prototyping when only amortized cost matters. Rarely the best production choice.
Implementation (Python)
class CircularQueue:
"""FIFO queue using a circular buffer.
Args:
capacity: Initial capacity (must be >= 1)
bounded: If True, fixed capacity (raises on overflow).
If False, doubles when full, halves at 1/4.
"""
def __init__(self, capacity: int = 8, bounded: bool = False):
if capacity < 1:
raise ValueError("Capacity must be at least 1")
self._buf = [None] * capacity
self._head = 0
self._size = 0
self._bounded = bounded
self._min_cap = capacity if bounded else 8
def enqueue(self, item):
"""Add item to the back. O(1) amortized (growable) or O(1) worst (bounded)."""
if self._size == len(self._buf):
if self._bounded:
raise OverflowError("Queue is full")
self._resize(len(self._buf) * 2)
tail = (self._head + self._size) % len(self._buf)
self._buf[tail] = item
self._size += 1
def dequeue(self):
"""Remove and return item from front. O(1) amortized."""
if self._size == 0:
raise IndexError("Queue is empty")
item = self._buf[self._head]
self._buf[self._head] = None # allow GC
self._head = (self._head + 1) % len(self._buf)
self._size -= 1
# Shrink at 1/4 to avoid thrashing
if not self._bounded and self._size > 0 and self._size <= len(self._buf) // 4:
new_cap = max(len(self._buf) // 2, self._min_cap)
if new_cap < len(self._buf):
self._resize(new_cap)
return item
def peek(self):
"""Return front item without removing. O(1)."""
if self._size == 0:
raise IndexError("Queue is empty")
return self._buf[self._head]
def isEmpty(self):
"""Check if queue is empty. O(1)."""
return self._size == 0
def _resize(self, new_cap):
"""Copy elements in logical order into new buffer. O(n)."""
new_buf = [None] * new_cap
for i in range(self._size):
new_buf[i] = self._buf[(self._head + i) % len(self._buf)]
self._buf = new_buf
self._head = 0
Key Design Points:
- Track
sizeexplicitly to distinguish empty (size == 0) from full (size == capacity). - Compute tail as
(head + size) % capacityrather than storing it separately. - Resize copies elements in logical order, starting at new index 0.
- Shrink at 1/4 capacity to prevent thrashing from alternating enqueue/dequeue near the 50% boundary.
- Clear dequeued slots to enable garbage collection of referenced objects.
Time Complexity: O(1) amortized for growable mode, O(1) worst-case for bounded mode.
Space Complexity: O(n) where n is the number of elements, with up to 4× slack between resizes in growable mode.