KatInterview

Build a FIFO Queue: Compare Linked List, Array, and Ring Buffer

Data Structure DesignModel answer
MediumModel answerData Structure Designqueuedata-structurescomplexity-analysis

Last 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 back
  • dequeue() – remove and return the item at the front
  • peek() – return the front item without removing it
  • isEmpty() – check if the queue contains no items

Compare three implementation strategies:

  1. Singly linked list with head and tail pointers
  2. Dynamic array with a head index to avoid shifting
  3. 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