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:
- 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.
- Allocator & pointer overhead: Every doubly linked node pays extra bytes for
prev/nextpointers plus heap-allocator headers and fragmentation, whereas a preallocated array pays zero per-element pointer tax. - 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.
- Access & queue mechanics: Contiguous buffers compute any
indexoffset inO(1)arithmetic, whereas linked lists requireO(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 mostcapacityintegers.enqueue(val: int) -> bool— Appendsvalto the back of the queue and returnsTrue; if the queue already holdscapacityitems, leaves existing items untouched and returnsFalse.dequeue() -> int— Removes and returns the front item, or returns-1when the queue is empty.get(index: int) -> int— Returns the item at 0-based logical offsetindexfrom the current front, or-1ifindex < 0orindexis greater than or equal to the number of items currently stored.is_empty() -> bool— ReturnsTruewhen0items are stored, elseFalse.is_full() -> bool— ReturnsTruewhencapacityitems are stored, elseFalse.
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^50 <= val <= 10^90 <= index <= capacity1 <= len(operations) == len(arguments) <= 2 * 10^5- Every operation after
"init"must run in strictO(1)time without reallocating storage.
Step-by-step walkthrough
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
CircularQueuewhere every call after__init__runs in strict worst-caseO(1)time without resizing storage.Here is each method's exact contract:
CircularQueue(capacity)preallocatescapacityslots (1 <= capacity <= 10^5).enqueue(val)writesval(0 <= val <= 10^9) at the logical tail and returnsTrue, or returnsFalsewithout modifying the buffer if already full.dequeue()removes and returns the front element, or-1when empty (-1cannot collide with valid non-negative elements).get(index)returns the element at 0-based offsetindexfrom the current front, or-1whenindexfalls outside[0, size - 1].is_empty()andis_full()test whether the current item count equals0orcapacity.
Compare arrays and linked lists on real hardware
Although a doubly linked list and a ring buffer share
O(1)asymptoticenqueueanddequeuebounds, actual CPU hardware separates them sharply across four dimensions:- 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.nextuntilnodearrives (pointer chasing), stalling ~60–100 ns on cold cache misses. - 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. - 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.
- Access and mutation mechanics: Computing offset
indexin a contiguous buffer takes a singleO(1)address calculation, whereas walkingindexlinks takesO(index)pointer hops. Splicing into the middle of a linked list isO(1)only when you already hold a pointer to that node; locating the spot by position still costsO(n)pointer hops, whereas shifting contiguous bytes leverages vectorizedmemmove.
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
listslots store contiguous 8-byte object pointers rather than raw unboxed ints unlessarray.arrayis used, soCircularQueuedemonstrates the exact ring-buffer index mechanics used with raw arrays in C++ or Rust.)- 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
Why wraparound eliminates shifting
Calling
pop(0)on a regular list shifts every remaining item one slot left inO(n)time. Simply advancing aheadindex without shifting fixesdequeue, 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 - 1back to slot0using modulo arithmetic (% capacity). Advancing past the last physical slot wraps seamlessly around to index0:Physical slots for capacity = 3: slot 0 -> slot 1 -> slot 2 -> (2 + 1) % 3 = slot 0 (wraps around!)Store `head` and `size` to separate empty from full
Tracking only
head(front slot) andtail(next write slot) creates an ambiguity oncapacity = 3:- When empty,
head = 0andtail = 0(head == tail). - After 3 enqueues,
tailsteps0 -> 1 -> 2 -> 0, so when full,head = 0andtail = 0(head == tailagain!).
Maintaining
headalongsidesize(the live element count) removes that ambiguity without sacrificing a spare slot:- Empty means
size == 0; full meanssize == capacity. - With
sizelive items starting athead, the next write position is alwaystail = (head + size) % capacity. dequeuereadsbuffer[head], stepshead = (head + 1) % capacity, and decrementssize. Stale numbers left in freed slots remain invisible becausesizebounds 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- When empty,
Add O(1) offset lookup and occupancy checks
Logical offset
0lives athead, offset1lives at(head + 1) % capacity, and general offsetindexlives at(head + index) % capacity—deliveringO(1)indexed lookup that node-based queues cannot provide.Guard
indexagainstself.size, notself.capacity: as shown in Example 2, whencapacity = 2andsize = 1,get(1)must return-1rather 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.capacityWire the command runner and trace Example 1
The driver
circular_queue(operations, arguments)instantiatesCircularQueueon"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 resultsLet'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] TrueNotice how
enqueue(90)wrapped around to reuse physical slot0, whileget(0)andget(2)translated logical offsets fromhead = 1into physical slots1and0inO(1)time.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:
enqueue(50),enqueue(60),enqueue(70)write to(head + size) % 3-> slots0, 1, 2, reachinghead = 0, size = 3([50, 60, 70]).dequeue()returnsbuffer[0] = 50and stepshead = (0 + 1) % 3 = 1withsize = 2(logical queue[60, 70]).enqueue(90)writes attail = (1 + 2) % 3 = 0, wrapping around into slot0(bufferholds[90, 60, 70]withhead = 1, size = 3).get(2)asks for offset2from the front, computes(1 + 2) % 3 = 0, and reads90in one step.
Complexity
Let c be capacity and q be len(operations):
- Time —
O(c)once forinit, and strictO(1)worst-case perenqueue,dequeue,get,is_empty, andis_full(O(c + q)total): Allocatingczeroed slots happens once during initialization. Every subsequent call executes a constant number of integer comparisons, one% cremainder, and at most one list slot access—with zero element shifting and zero resize pauses. - Space —
O(c)auxiliary space (plusO(q)for the returned results list):self.bufferholds exactlycpreallocated slots plus three integer fields (capacity,head,size), never allocating new nodes no matter how many items cycle through.
Edge cases
- Calling
dequeueorgetwhen empty:self.size == 0returns-1immediately without mutatingheadorsize. - Calling
enqueuewhen full:self.size == self.capacityreturnsFalseimmediately without clobberingbuffer[head]. get(index)belowcapacityyet at or pastsize: In Example 2,capacity = 2andsize = 1, soget(1)returns-1rather than leaking inactive slot1(including stale values left behind by earlierdequeuecalls).get(index)atcapacityor negative: Checkingindex < 0 or index >= self.sizerejects both negative offsets and offsets>= capacity.- Storing
0as an actual element: Occupancy is tracked bysizerather than sentinel values insidebuffer, so0behaves like any positive value. - Single-slot capacity (
capacity = 1):(0 + 1) % 1evaluates to0, cleanly alternatingsizebetween0and1across repeated cycles.
Common mistakes
- Storing
headandtailwithoutsize(or without a dedicated empty slot): Empty and full buffers both havehead == tail, causing full buffers to look empty or overwrite unread items. - Bounding
getbyself.capacityinstead ofself.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 firstdequeueadvancesheadpast0. - Implementing
dequeuewithlist.pop(0): Quietly degrades each removal fromO(1)toO(n)due to left-shifting all remaining items. - Delegating to
collections.deque: Python'sdequelinks 64-item blocks in a doubly linked list, sod[index]near the middle traverses block pointers inO(n)time instead ofO(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] = Noneondequeueso garbage collection is not delayed until wraparound.
Alternative approaches
- One wasted sentinel slot (
capacity + 1array): Allocatecapacity + 1slots and store onlyheadandtail, treatinghead == tailas empty and(tail + 1) % (capacity + 1) == headas full. Avoiding a sharedsizevariable 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^kand let monotonic countersheadandtailincrement without modulo: occupancy istail - head, and physical slot lookup uses fast bitwiseidx & (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
Belements (sayB = 32or64, spanning one or two cache lines) plus a local count inside every linked node. Linear traversals readBcontiguous items per pointer hop—shrinking pointer overhead and cache misses by roughlyBx—while middle insertions or deletions shift at mostBitems within a single small chunk (splitting full chunks or coalescing sparse neighbors inO(B)time) rather than shifting allnitems 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
tailand consumerhead, 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 paddinghead,tail, and per-slot state to 64-byte boundaries (alignas(64)in C++,@Contendedin 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::listor 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 inO(1)time, or kernel run-queues that splice thread structs with zero heap allocation. When only stable handles (notO(1)middle splicing) are needed, integer indices into a contiguous arena ("slot map") or chunkedstd::dequestorage often preserve stability with far better cache locality.
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?
- Why can concurrent array queues suffer from cache-line ping-ponging (false sharing) across CPU cores, and how does memory alignment fix it?
- In what situations do stable element addresses make node-based lists mandatory over resizable contiguous vectors?
Similar questions
- Compile-Time Merging of C++ Index Sequences
- Safe Regular-File Counting Across Arbitrary Paths
- Evaluating Redis Caching Against Relational Index Tuning
- Sorted Contiguous Container With Move Semantics
- Python Runtime Semantics, Memory, and Concurrency
- Database Index Mechanics and Over-Indexing Trade-Offs
More Squarepoint interview questions
- Maximum Revenue Under Stock-Indexed Pricing Medium
- Replay Guarded Key-Value Store Commands Easy
- Contrasting Bonds, Common Stock, and Dividend Policy Medium Pro
- First-Drawer Win Probability With Tied-Rank Reshuffles Medium Pro
- Compile-Time Merging of C++ Index Sequences Medium Pro
- Safe Regular-File Counting Across Arbitrary Paths Medium Pro
- Even-Product Triplets Under a Modulus Medium Pro
- Counting Staircase Sequences With Custom Jumps Medium Pro
- Sorted Contiguous Container With Move Semantics Medium Pro
- OLS Market Beta From Paired Return Series Medium Pro