Fixed-Buffer Circular Queue vs Linked-Node Storage

Medium · Software Engineering Fundamentals · Quantitative Researcher · Technical Screen

Problem Statement

Selecting between a contiguous array and a pointer-linked list in latency-sensitive software requires looking past Big-O notation to how modern CPUs and memory allocators actually work:

  1. CPU caches & prefetching: Contiguous slots pack multiple items into a single 64-byte cache line and trigger sequential hardware prefetching, whereas linked nodes jump to unpredictable addresses and stall on cold cache misses.
  2. Allocator & pointer overhead: Every doubly linked node pays extra bytes for prev/next pointers plus heap-allocator headers and fragmentation, whereas a preallocated array pays zero per-element pointer tax.
  3. Address stability: Linked nodes keep fixed memory addresses when neighbors are added or removed, whereas resizable vectors relocate elements when capacity grows and shift elements on middle edits.
  4. Access & queue mechanics: Contiguous buffers compute any index offset in O(1) arithmetic, whereas linked lists require O(index) pointer hops.

To put these principles into practice, implement a fixed-size ring-buffer FIFO queue CircularQueue and its command driver circular_queue(operations, arguments) so that every operation after initialization runs in strict worst-case O(1) time with zero dynamic buffer resizing.

CircularQueue supports six methods:

  • CircularQueue(capacity: int) — Allocates fixed storage holding at most capacity integers.
  • enqueue(val: int) -> bool — Appends val to the back of the queue and returns True; if the queue already holds capacity items, leaves existing items untouched and returns False.
  • dequeue() -> int — Removes and returns the front item, or returns -1 when the queue is empty.
  • get(index: int) -> int — Returns the item at 0-based logical offset index from the current front, or -1 if index < 0 or index is greater than or equal to the number of items currently stored.
  • is_empty() -> bool — Returns True when 0 items are stored, else False.
  • is_full() -> bool — Returns True when capacity items are stored, else False.

circular_queue(operations, arguments) executes paired command names and argument lists in order ("init" with [capacity] appending None to the output list, "enqueue" with [val], "dequeue" with [], "get" with [index], "is_empty" with [], and "is_full" with []) and returns the list of outputs.

Examples

Example 1

operations = ["init", "enqueue", "enqueue", "enqueue", "enqueue", "dequeue", "enqueue", "get", "get", "is_full"]
arguments  = [[3],    [50],      [60],      [70],      [80],      [],        [90],      [0],   [2],   []]
# Output: [None, True, True, True, False, 50, True, 60, 90, True]

Walk-through: A 3-slot queue fills up with [50, 60, 70], so enqueue(80) returns False without overwriting 50. Calling dequeue() removes 50 from slot 0, freeing space so enqueue(90) wraps around to slot 0 and forms the logical queue [60, 70, 90]. Offsets 0 and 2 from the front then read 60 and 90, and is_full() returns True.

Example 2

operations = ["init", "is_empty", "dequeue", "enqueue", "get", "get", "dequeue", "is_empty"]
arguments  = [[2],    [],         [],        [15],      [0],   [1],   [],        []]
# Output: [None, True, -1, True, 15, -1, 15, True]

Walk-through: Starting empty with capacity 2, is_empty() is True and dequeue() returns -1. After enqueue(15), only 1 item is live, so get(0) returns 15 while get(1) returns -1 even though 1 < capacity. Dequeuing 15 empties the queue again.

Constraints

  • 1 <= capacity <= 10^5
  • 0 <= val <= 10^9
  • 0 <= index <= capacity
  • 1 <= len(operations) == len(arguments) <= 2 * 10^5
  • Every operation after "init" must run in strict O(1) time without reallocating storage.

Step-by-step walkthrough

  1. Understand the goal and queue contract

    We want to connect hardware-level memory trade-offs (contiguous arrays versus linked nodes) to a concrete implementation: a fixed-size first-in, first-out (FIFO) buffer CircularQueue where every call after __init__ runs in strict worst-case O(1) time without resizing storage.

    Here is each method's exact contract:

    • CircularQueue(capacity) preallocates capacity slots (1 <= capacity <= 10^5).
    • enqueue(val) writes val (0 <= val <= 10^9) at the logical tail and returns True, or returns False without modifying the buffer if already full.
    • dequeue() removes and returns the front element, or -1 when empty (-1 cannot collide with valid non-negative elements).
    • get(index) returns the element at 0-based offset index from the current front, or -1 when index falls outside [0, size - 1].
    • is_empty() and is_full() test whether the current item count equals 0 or capacity.
  2. Compare arrays and linked lists on real hardware

    Although a doubly linked list and a ring buffer share O(1) asymptotic enqueue and dequeue bounds, actual CPU hardware separates them sharply across four dimensions:

    1. Cache lines and prefetching: CPUs transfer RAM in fixed cache lines (64 bytes on typical 64-bit chips). One 64-byte line packs 16 adjacent 4-byte integers, and the hardware prefetcher spots sequential index strides and streams upcoming lines into L1/L2 cache (~1 ns latency) ahead of time. Linked-list nodes live at scattered heap addresses, and the CPU cannot even request node.next until node arrives (pointer chasing), stalling ~60–100 ns on cold cache misses.
    2. Memory and allocator overhead: Holding a single 4-byte int inside a 64-bit doubly linked node adds two 8-byte links (prev, next), alignment padding to 24 bytes, and allocator metadata (~32 bytes per node—an 8x blow-up), plus per-push allocator work and heap fragmentation (tiny unusable gaps between freed blocks). A preallocated buffer makes one allocation up front with zero pointer overhead per slot.
    3. Address stability: Once allocated, a linked node never moves in memory while neighbors come and go. By contrast, dynamically growing vectors copy elements to a larger block when capacity doubles—invalidating raw element pointers—and middle edits shift trailing items.
    4. Access and mutation mechanics: Computing offset index in a contiguous buffer takes a single O(1) address calculation, whereas walking index links takes O(index) pointer hops. Splicing into the middle of a linked list is O(1) only when you already hold a pointer to that node; locating the spot by position still costs O(n) pointer hops, whereas shifting contiguous bytes leverages vectorized memmove.
    Contiguous buffer (one 64-byte cache line packs 16 int32 values):
    +----+----+----+----+----+----+----+----+ ...
    | 50 | 60 | 70 | 90 | .. | .. | .. | .. |     sequential & hardware-prefetched
    +----+----+----+----+----+----+----+----+ ...
    
    Doubly linked list (scattered heap nodes, two 8-byte pointers per value):
    [prev|50|next] ---> (RAM hop) ---> [prev|60|next] ---> (RAM hop) ---> [prev|70|next]
    

    (Note: standard Python list slots store contiguous 8-byte object pointers rather than raw unboxed ints unless array.array is used, so CircularQueue demonstrates the exact ring-buffer index mechanics used with raw arrays in C++ or Rust.)

  3. Why wraparound eliminates shifting

    Calling pop(0) on a regular list shifts every remaining item one slot left in O(n) time. Simply advancing a head index without shifting fixes dequeue, yet quickly marches off the right end of the array even while freed slots sit unused on the left.

    A ring buffer (circular array) connects slot capacity - 1 back to slot 0 using modulo arithmetic (% capacity). Advancing past the last physical slot wraps seamlessly around to index 0:

    Physical slots for capacity = 3:
    slot 0 -> slot 1 -> slot 2 -> (2 + 1) % 3 = slot 0 (wraps around!)
    
  4. Store `head` and `size` to separate empty from full

    Tracking only head (front slot) and tail (next write slot) creates an ambiguity on capacity = 3:

    • When empty, head = 0 and tail = 0 (head == tail).
    • After 3 enqueues, tail steps 0 -> 1 -> 2 -> 0, so when full, head = 0 and tail = 0 (head == tail again!).

    Maintaining head alongside size (the live element count) removes that ambiguity without sacrificing a spare slot:

    • Empty means size == 0; full means size == capacity.
    • With size live items starting at head, the next write position is always tail = (head + size) % capacity.
    • dequeue reads buffer[head], steps head = (head + 1) % capacity, and decrements size. Stale numbers left in freed slots remain invisible because size bounds every read.
    class CircularQueue:
        def __init__(self, capacity: int):
            # buffer: fixed-size list of 'capacity' integer slots allocated once up front, e.g. [50, 60, 70]
            self.buffer: List[int] = [0] * capacity
            self.capacity: int = capacity
            # head: physical index in self.buffer of the front element (0 <= head < capacity)
            self.head: int = 0
            # size: count of live elements currently stored (0 <= size <= capacity),
            # which distinguishes empty (size == 0) from full (size == capacity) without wasting a slot.
            self.size: int = 0
    
        def enqueue(self, val: int) -> bool:
            # Reject new items when full rather than overwriting the oldest item.
            if self.size == self.capacity:
                return False
    
            # Wrap around the end of the fixed buffer using modulo arithmetic.
            tail = (self.head + self.size) % self.capacity
            self.buffer[tail] = val
            self.size += 1
            return True
    
        def dequeue(self) -> int:
            if self.size == 0:
                return -1
    
            # Read the front slot and advance head circularly; no elements are shifted.
            front_val = self.buffer[self.head]
            self.head = (self.head + 1) % self.capacity
            self.size -= 1
            return front_val
    
  5. Add O(1) offset lookup and occupancy checks

    Logical offset 0 lives at head, offset 1 lives at (head + 1) % capacity, and general offset index lives at (head + index) % capacity—delivering O(1) indexed lookup that node-based queues cannot provide.

    Guard index against self.size, not self.capacity: as shown in Example 2, when capacity = 2 and size = 1, get(1) must return -1 rather than exposing uninitialized or previously dequeued slot contents.

        def get(self, index: int) -> int:
            # Check against self.size (live elements), not self.capacity, so dequeued slots stay hidden.
            if index < 0 or index >= self.size:
                return -1
            physical_slot = (self.head + index) % self.capacity
            return self.buffer[physical_slot]
    
        def is_empty(self) -> bool:
            return self.size == 0
    
        def is_full(self) -> bool:
            return self.size == self.capacity
    
  6. Wire the command runner and trace Example 1

    The driver circular_queue(operations, arguments) instantiates CircularQueue on "init" and records each method's return value:

    def circular_queue(operations: List[str], arguments: List[List[int]]) -> List:
        queue: Optional[CircularQueue] = None
        results = []
    
        # Execute each recorded queue operation in sequence and collect its output.
        for op, args in zip(operations, arguments):
            if op == "init":
                queue = CircularQueue(args[0])
                results.append(None)
            elif op == "enqueue":
                results.append(queue.enqueue(args[0]))
            elif op == "dequeue":
                results.append(queue.dequeue())
            elif op == "get":
                results.append(queue.get(args[0]))
            elif op == "is_empty":
                results.append(queue.is_empty())
            elif op == "is_full":
                results.append(queue.is_full())
            else:
                raise ValueError(f"unknown operation: {op}")
    
        return results
    

    Let's trace Example 1 (capacity = 3) across every call:

    Call          Slot math                    buffer        head  size  Logical queue   Return
    ------------  ---------------------------  ------------  ----  ----  --------------  ------
    init(3)       allocate 3 slots             [0, 0, 0]      0     0    []              None
    enqueue(50)   tail = (0 + 0) % 3 = 0       [50, 0, 0]     0     1    [50]            True
    enqueue(60)   tail = (0 + 1) % 3 = 1       [50, 60, 0]    0     2    [50, 60]        True
    enqueue(70)   tail = (0 + 2) % 3 = 2       [50, 60, 70]   0     3    [50, 60, 70]    True
    enqueue(80)   size == 3 (full!)            [50, 60, 70]   0     3    [50, 60, 70]    False
    dequeue()     read slot 0; head=(0+1)%3=1  [50, 60, 70]   1     2    [60, 70]        50
    enqueue(90)   tail = (1 + 2) % 3 = 0       [90, 60, 70]   1     3    [60, 70, 90]    True
    get(0)        slot = (1 + 0) % 3 = 1       [90, 60, 70]   1     3    [60, 70, 90]    60
    get(2)        slot = (1 + 2) % 3 = 0       [90, 60, 70]   1     3    [60, 70, 90]    90
    is_full()     size == 3                    [90, 60, 70]   1     3    [60, 70, 90]    True
    

    Notice how enqueue(90) wrapped around to reuse physical slot 0, while get(0) and get(2) translated logical offsets from head = 1 into physical slots 1 and 0 in O(1) time.

  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    class CircularQueue:
        def __init__(self, capacity: int):
            # buffer: fixed-size list of 'capacity' integer slots allocated once up front, e.g. [50, 60, 70]
            self.buffer: List[int] = [0] * capacity
            self.capacity: int = capacity
            # head: physical index in self.buffer of the front element (0 <= head < capacity)
            self.head: int = 0
            # size: count of live elements currently stored (0 <= size <= capacity),
            # which distinguishes empty (size == 0) from full (size == capacity) without wasting a slot.
            self.size: int = 0
    
        def enqueue(self, val: int) -> bool:
            # Reject new items when full rather than overwriting the oldest item.
            if self.size == self.capacity:
                return False
    
            # Wrap around the end of the fixed buffer using modulo arithmetic.
            tail = (self.head + self.size) % self.capacity
            self.buffer[tail] = val
            self.size += 1
            return True
    
        def dequeue(self) -> int:
            if self.size == 0:
                return -1
    
            # Read the front slot and advance head circularly; no elements are shifted.
            front_val = self.buffer[self.head]
            self.head = (self.head + 1) % self.capacity
            self.size -= 1
            return front_val
    
        def get(self, index: int) -> int:
            # Check against self.size (live elements), not self.capacity, so dequeued slots stay hidden.
            if index < 0 or index >= self.size:
                return -1
            physical_slot = (self.head + index) % self.capacity
            return self.buffer[physical_slot]
    
        def is_empty(self) -> bool:
            return self.size == 0
    
        def is_full(self) -> bool:
            return self.size == self.capacity
    
    
    def circular_queue(operations: List[str], arguments: List[List[int]]) -> List:
        queue: Optional[CircularQueue] = None
        results = []
    
        # Execute each recorded queue operation in sequence and collect its output.
        for op, args in zip(operations, arguments):
            if op == "init":
                queue = CircularQueue(args[0])
                results.append(None)
            elif op == "enqueue":
                results.append(queue.enqueue(args[0]))
            elif op == "dequeue":
                results.append(queue.dequeue())
            elif op == "get":
                results.append(queue.get(args[0]))
            elif op == "is_empty":
                results.append(queue.is_empty())
            elif op == "is_full":
                results.append(queue.is_full())
            else:
                raise ValueError(f"unknown operation: {op}")
    
        return results
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of reading numbers printed side by side along a single strip of paper (an array) versus following scavenger-hunt slips scattered across random rooms (a linked list). Even when both structures perform queue updates in O(1) steps on paper, CPU hardware fetches RAM in contiguous blocks called cache lines (typically 64 bytes at a time), so neighboring array slots enter fast CPU cache together with zero per-item pointer memory or heap allocations. To turn a fixed-length array into a first-in, first-out (FIFO) queue without shifting elements on removal, we treat it as a ring buffer (circular array): modulo arithmetic (% capacity) wraps indices past the end of the array smoothly back to slot 0, like a clock hand passing 12.

Simpler queue attempts stumble on either runtime or memory costs: list.pop(0) shifts every remaining element left in O(n) time, while a linked-node queue allocates a separate heap object carrying two 8-byte pointers on every push, suffers pointer-chasing cache misses, and still needs O(n) hops to answer get(index). Even in a ring buffer, keeping only head and tail indices hits a classic snag because head == tail holds when the buffer is empty and when it is completely full; storing head and size instead lets us use all capacity slots cleanly.

Trace Example 1's 3-slot CircularQueue(3) across a wraparound:

  1. enqueue(50), enqueue(60), enqueue(70) write to (head + size) % 3 -> slots 0, 1, 2, reaching head = 0, size = 3 ([50, 60, 70]).
  2. dequeue() returns buffer[0] = 50 and steps head = (0 + 1) % 3 = 1 with size = 2 (logical queue [60, 70]).
  3. enqueue(90) writes at tail = (1 + 2) % 3 = 0, wrapping around into slot 0 (buffer holds [90, 60, 70] with head = 1, size = 3).
  4. get(2) asks for offset 2 from the front, computes (1 + 2) % 3 = 0, and reads 90 in one step.

Complexity

Let c be capacity and q be len(operations):

  • Time — O(c) once for init, and strict O(1) worst-case per enqueue, dequeue, get, is_empty, and is_full (O(c + q) total): Allocating c zeroed slots happens once during initialization. Every subsequent call executes a constant number of integer comparisons, one % c remainder, and at most one list slot access—with zero element shifting and zero resize pauses.
  • Space — O(c) auxiliary space (plus O(q) for the returned results list): self.buffer holds exactly c preallocated slots plus three integer fields (capacity, head, size), never allocating new nodes no matter how many items cycle through.

Edge cases

  • Calling dequeue or get when empty: self.size == 0 returns -1 immediately without mutating head or size.
  • Calling enqueue when full: self.size == self.capacity returns False immediately without clobbering buffer[head].
  • get(index) below capacity yet at or past size: In Example 2, capacity = 2 and size = 1, so get(1) returns -1 rather than leaking inactive slot 1 (including stale values left behind by earlier dequeue calls).
  • get(index) at capacity or negative: Checking index < 0 or index >= self.size rejects both negative offsets and offsets >= capacity.
  • Storing 0 as an actual element: Occupancy is tracked by size rather than sentinel values inside buffer, so 0 behaves like any positive value.
  • Single-slot capacity (capacity = 1): (0 + 1) % 1 evaluates to 0, cleanly alternating size between 0 and 1 across repeated cycles.

Common mistakes

  • Storing head and tail without size (or without a dedicated empty slot): Empty and full buffers both have head == tail, causing full buffers to look empty or overwrite unread items.
  • Bounding get by self.capacity instead of self.size: Exposes uninitialized zeros or already-dequeued values sitting in unused slots.
  • Indexing self.buffer[index] directly instead of (self.head + index) % self.capacity: Breaks as soon as the first dequeue advances head past 0.
  • Implementing dequeue with list.pop(0): Quietly degrades each removal from O(1) to O(n) due to left-shifting all remaining items.
  • Delegating to collections.deque: Python's deque links 64-item blocks in a doubly linked list, so d[index] near the middle traverses block pointers in O(n) time instead of O(1).
  • Retaining dead object references in managed languages: Integers are tiny, whereas a general object ring buffer in Python or Java should clear self.buffer[self.head] = None on dequeue so garbage collection is not delayed until wraparound.

Alternative approaches

  • One wasted sentinel slot (capacity + 1 array): Allocate capacity + 1 slots and store only head and tail, treating head == tail as empty and (tail + 1) % (capacity + 1) == head as full. Avoiding a shared size variable helps in single-producer, single-consumer lock-free queues where each thread writes only its own index.
  • Power-of-two capacity with wrapping bitwise mask: Round buffer length up to P = 2^k and let monotonic counters head and tail increment without modulo: occupancy is tail - head, and physical slot lookup uses fast bitwise idx & (P - 1) instead of integer division.

Follow-up questions

  • How does storing small fixed-length arrays inside each list node (an unrolled linked list) trade off sequential scan speed against middle insertions? An unrolled linked list packs up to B elements (say B = 32 or 64, spanning one or two cache lines) plus a local count inside every linked node. Linear traversals read B contiguous items per pointer hop—shrinking pointer overhead and cache misses by roughly Bx—while middle insertions or deletions shift at most B items within a single small chunk (splitting full chunks or coalescing sparse neighbors in O(B) time) rather than shifting all n items of one monolithic array.
  • Why can concurrent array queues suffer from cache-line ping-ponging (false sharing) across CPU cores, and how does memory alignment fix it? Multi-core CPUs enforce cache coherence (keeping per-core caches synchronized) at whole 64-byte cache-line granularity: any core writing to a cache line invalidates every other core's cached copy of those 64 bytes. False sharing occurs when independent hot fields—such as producer tail and consumer head, or neighboring small ring-buffer slots written by different cores—share a 64-byte line, forcing cores to repeatedly bounce that cache line back and forth. Aligning and padding head, tail, and per-slot state to 64-byte boundaries (alignas(64) in C++, @Contended in Java) gives each hot field its own cache line and eliminates cross-core invalidation traffic.
  • In what situations do stable element addresses make node-based lists mandatory over resizable contiguous vectors? Reference stability guarantees that pointers or iterators to live elements remain valid while other elements are inserted or erased. Node-based lists (std::list or intrusive lists where link pointers sit directly inside domain structs) become essential when external indexes hold direct pointers into the collection during mutations—for example, an LRU cache whose hash table stores node pointers to splice any accessed entry to the front in O(1) time, or kernel run-queues that splice thread structs with zero heap allocation. When only stable handles (not O(1) middle splicing) are needed, integer indices into a contiguous arena ("slot map") or chunked std::deque storage often preserve stability with far better cache locality.

Follow-up questions

Similar questions

More Squarepoint interview questions

All 38 Squarepoint questions →