Design Circular Queue solution explained
Design Circular Queue asks for a first-in, first-out queue with a fixed capacity, where every operation runs in O(1) and the storage is one array that wraps around. Keep a head index and a count: the front is at head, the next free slot is (head + count) mod capacity, and the rear is one before that. Storing the count is what lets you tell a full queue from an empty one without wasting a slot.
By Evin JohnPublished 8 min read
The task, restated
Build a queue object created with a capacity k. enqueue(value) adds a value at the back and returns true, or returns false if the queue already holds k values. dequeue() removes the value at the front and returns true, or false if the queue is empty. front() and rear() return the first and last values without removing them, or -1 when the queue is empty, since values are non-negative. is_empty() and is_full() report the obvious. All operations should take constant time, and the queue should reuse the space freed by dequeues instead of growing.
| Call | Returns | Array cells | head, count |
|---|---|---|---|
| enqueue(5) | true | [5, _, _] | 0, 1 |
| enqueue(6) | true | [5, 6, _] | 0, 2 |
| enqueue(7) | true | [5, 6, 7] | 0, 3 |
| enqueue(8) | false | [5, 6, 7] | 0, 3, full |
| dequeue() | true | [5, 6, 7] | 1, 2; the 5 is now ignored |
| enqueue(8) | true | [8, 6, 7] | 1, 3; 8 wraps into cell 0 |
| front() | 6 | cell at head | |
| rear() | 8 | cell (1 + 3 - 1) mod 3 = 0 |
Note row five: dequeue does not erase anything. It only moves head forward. The stale 5 stays in the array until an enqueue overwrites it, which is fine because no index calculation ever reads it. Interviewers like to see that you are not wasting time clearing cells.
Where ring buffers show up
Circular queues are everywhere in systems code: audio and network buffers, keyboard input queues, the last N log lines, rate limiters that keep timestamps of recent requests, and moving averages over a stream. In interviews, the problem checks whether you can manage indexes without off-by-one errors and whether you know why the naive list-based queue is slow. Common follow-ups:
- Make it a deque. Add insert_front and delete_last; moving head backward is (head - 1 + k) mod k.
- Overwrite the oldest value when full instead of rejecting, as a log buffer would. Write at the next slot and advance head when the queue was already full.
- Make it thread-safe. One lock around each method, or two condition variables if callers should wait for space or data. Saying this is enough unless the role is systems-heavy.
- Let it grow. When full, copy the items in order into an array twice the size and reset head to 0. That is how dynamic deques are built.
A slow baseline: a list that shifts
The quickest correct version wraps a dynamic list: append to enqueue, remove index 0 to dequeue, and compare the length with k for is_full. It passes every functional test, but removing the first element of an array-backed list shifts every remaining element, so dequeue costs O(n). Python's list.pop(0) and JavaScript's Array.prototype.shift behave this way in general. State that, then move to the ring buffer.
class ShiftingQueue:
def __init__(self, k):
self.k = k
self.items = []
def enqueue(self, value):
if len(self.items) == self.k:
return False
self.items.append(value)
return True
def dequeue(self):
if not self.items:
return False
self.items.pop(0)
return True
def front(self):
return self.items[0] if self.items else -1
def rear(self):
return self.items[-1] if self.items else -1Optimal approach: head index plus count
Allocate an array of k cells once. head is the index of the front value. count is how many values are stored. The slot for the next enqueue is (head + count) mod k, and the rear value sits at (head + count - 1) mod k. Enqueue writes and increments count; dequeue advances head by one, wrapping with mod k, and decrements count. Full is count == k and empty is count == 0, so there is never any doubt.
class CircularQueue:
def __init__(self, k):
self.cells = [0] * k
self.head = 0
self.count = 0
def enqueue(self, value):
if self.count == len(self.cells):
return False
self.cells[(self.head + self.count) % len(self.cells)] = value
self.count += 1
return True
def dequeue(self):
if self.count == 0:
return False
self.head = (self.head + 1) % len(self.cells)
self.count -= 1
return True
def front(self):
return -1 if self.count == 0 else self.cells[self.head]
def rear(self):
if self.count == 0:
return -1
return self.cells[(self.head + self.count - 1) % len(self.cells)]
def is_empty(self):
return self.count == 0
def is_full(self):
return self.count == len(self.cells)class CircularQueue {
constructor(k) {
this.cells = new Array(k).fill(0);
this.head = 0;
this.count = 0;
}
enqueue(value) {
if (this.count === this.cells.length) return false;
this.cells[(this.head + this.count) % this.cells.length] = value;
this.count += 1;
return true;
}
dequeue() {
if (this.count === 0) return false;
this.head = (this.head + 1) % this.cells.length;
this.count -= 1;
return true;
}
front() {
return this.count === 0 ? -1 : this.cells[this.head];
}
rear() {
if (this.count === 0) return -1;
return this.cells[(this.head + this.count - 1) % this.cells.length];
}
isEmpty() {
return this.count === 0;
}
isFull() {
return this.count === this.cells.length;
}
}Every index expression adds before taking the remainder and never subtracts below zero, which matters in JavaScript, where a negative number mod k stays negative. The rear formula subtracts one, but it only runs when count is at least 1, so head + count - 1 is never negative.
The head-and-tail version, and its trap
Many textbooks store head and tail instead of a count, where tail is the next free slot. Enqueue writes at tail and moves it forward; dequeue moves head forward. The trouble appears when the two pointers meet: head == tail after the last dequeue means empty, and head == tail after the k-th enqueue means full. There are two standard fixes. Allocate k + 1 cells and call the queue full when (tail + 1) mod (k + 1) == head, wasting one slot on purpose. Or keep a boolean or a count next to the pointers, which is the design above. Either is acceptable; what costs points is not noticing the ambiguity at all.
Time and space
| Design | enqueue | dequeue | front / rear | Space |
|---|---|---|---|---|
| Dynamic list, remove from index 0 | O(1) amortized | O(n) | O(1) | O(n) |
| Linked list with head and tail nodes | O(1) | O(1) | O(1) | O(n) plus a node per value |
| Ring buffer, head plus count | O(1) | O(1) | O(1) | O(k), allocated once |
| Ring buffer, k + 1 cells | O(1) | O(1) | O(1) | O(k + 1) |
The linked list is also O(1), and it is a fair answer if you mention it. The array wins in practice because it allocates once and keeps values next to each other in memory, which is why buffers in drivers and runtimes are rings rather than lists.
Edge cases
- Capacity 1: enqueue fills it, the next enqueue fails, dequeue empties it, and front equals rear while it holds a value.
- Capacity 0: every enqueue returns false and every front or rear returns -1. The code above checks fullness before any modulo, so it never divides by zero.
- Dequeue on an empty queue returns false and leaves head where it was.
- Long runs of alternating enqueue and dequeue: head and the write slot keep circling, and the modulo keeps them in range indefinitely.
- Rear right after a wrap: the rear index is smaller than head, which is correct and should not be special-cased.
Mistakes to avoid
- Using head == tail as the only emptiness test with a k-cell array, so a full queue reports empty.
- Computing the rear as tail - 1 without wrapping, which reads index -1 after tail returns to 0. In Python that silently reads the last cell, which hides the bug.
- Moving head before checking for emptiness in dequeue.
- Clearing cells on dequeue and then treating 0 as empty, which breaks once 0 is a legal value.
- Reaching for a growable list and calling it a circular queue. The point is the fixed array.
How to explain it out loud
Fictional example
- Candidate
- A list with pop from the front would work but dequeue is linear, so I'll use a fixed array of size k as a ring.
- Candidate
- I'll store head and a count instead of head and tail, because with only two pointers head equals tail is ambiguous: it could mean empty or full.
- Candidate
- Next write goes to head plus count mod k, rear is one before that, and dequeue just moves head forward. Everything is constant time and the array never grows.
Related problems
Implement Queue Using Stacks builds the same first-in, first-out behavior from a different starting material and leads to an amortized argument instead of index math. Design HashMap is the other classic build-it-from-an-array question, with collisions in place of wraparound. Binary Tree Level Order Traversal is a good place to use a queue once you have built one.
Where Natively helps
For short design questions, the value of practice is in saying the edge cases before the interviewer does. Natively, on Mac or Windows, transcribes your spoken walkthrough so you can see afterward whether you raised the full-versus-empty issue unprompted. In practice it can also read the problem from a screenshot and propose code, which is handy for comparing your index math with another version. The AI interview assistant page has the details.
Questions people ask
How do you implement a circular queue?
Allocate an array of k cells and keep a head index and a count. Enqueue writes at (head + count) mod k, dequeue moves head forward by one mod k, and the rear is at (head + count - 1) mod k.
How do you tell a full circular queue from an empty one?
With only head and tail pointers, head equal to tail is ambiguous. Keep a count, keep a full flag, or allocate k + 1 cells and treat the queue as full when the next tail position equals head.
What is the time complexity of a circular queue?
Every operation is O(1), and the queue uses O(k) space allocated once. A list that removes from the front costs O(n) per dequeue instead.
Where are circular buffers used in practice?
Audio and network buffers, input queues, logs that keep the last N lines, rate limiters and moving averages over a stream all use ring buffers.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
