Design Circular Queue in TypeScript: Reusing the Same Slots

A queue sounds like a particularly polite array: new arrivals join the back, and the oldest item leaves first. The awkward part comes when we want a fixed amount of storage. Removing the first item should free somewhere useful, without making every remaining item shuffle along to fill the gap.
LeetCode's Design Circular Queue problem asks us to build that behaviour ourselves. I use an array, a head index, and a count. The array never grows. The indices wrap around instead, which is much less dramatic than moving all the furniture every time somebody leaves.
Keep the Order, Reuse the Space
The interface has six operations: insert at the rear, remove from the front, inspect either end, check whether the queue is empty, and check whether it is full. Insertions into a full queue return false. Removals from an empty queue also return false. Inspecting an empty queue returns -1.
The challenge permits capacities from 1 to 1,000 and stored integers from 0 to 1,000. There are at most 3,000 operation calls. Those details help: zero is a valid item, so we cannot use a zero‑filled slot to decide whether an item exists. The count must carry that information.
An array with push() and shift() makes a useful reference implementation. For this exercise, though, I want insertion and removal to do a bounded amount of work. Moving an array's remaining entries is unnecessary when the storage can stay still and the logical front can move.
In my Rotting Oranges walkthrough, an advancing head avoids removing entries from the front of a growing queue. A circular queue takes another step: it reuses the consumed slots, so a long sequence of operations doesn't require a longer backing array.
Two Numbers Explain the State
Let head identify the next item to remove, and let size count the live items. For capacity k, the useful invariant is that live item number i occupies (head + i) % k, for 0 <= i < size. Reading those positions in order gives the queue, even when its contents cross the end of the physical array.
The next insertion therefore belongs at (head + size) % k. The rear item, when one exists, is at (head + size - 1) % k. Removing an item advances head by one, wrapping back to zero when necessary, and reduces size.
I prefer keeping the count explicitly because it makes the two awkward states unambiguous. Empty means size === 0; full means size === k. With only two moving indices, the same index positions can represent either state unless we add another convention, such as reserving an unused slot. A count lets us use every allocated slot.
When the queue is empty, head can still point somewhere in the middle of the array. That is fine. It describes where the next item will go, rather than requiring a ceremonial reset to zero after every drain.
The TypeScript Implementation
The method names follow the challenge, including the capitalised Front and Rear. Class methods use arrow functions here, so passing one around doesn't lose its instance. The constructor rejects a non‑positive or fractional capacity; the stored values otherwise follow the problem's integer limits.
export class MyCircularQueue {
private readonly values: number[];
private head = 0;
private size = 0;
public constructor(private readonly capacity: number) {
if (!Number.isInteger(capacity) || capacity < 1) {
throw new RangeError('Capacity must be a positive integer.');
}
this.values = new Array<number>(capacity).fill(0);
}
public enQueue = (value: number): boolean => {
if (this.isFull()) return false;
const next = (this.head + this.size) % this.capacity;
this.values[next] = value;
this.size += 1;
return true;
};
public deQueue = (): boolean => {
if (this.isEmpty()) return false;
this.head = (this.head + 1) % this.capacity;
this.size -= 1;
return true;
};
public Front = (): number => {
return this.isEmpty() ? -1 : this.values[this.head]!;
};
public Rear = (): number => {
if (this.isEmpty()) return -1;
const rear = (this.head + this.size - 1) % this.capacity;
return this.values[rear]!;
};
public isEmpty = (): boolean => this.size === 0;
public isFull = (): boolean => this.size === this.capacity;
}Both mutating operations check their failure condition before changing anything. A failed insertion must not overwrite the oldest value, and a failed removal must not advance the head. Returning the right boolean whilst quietly damaging the next operation would be a rather unhelpful definition of success.
The non‑null assertions follow from the invariant. A nonempty queue has assigned its front and rear slots, and those indices are within the allocated array. The empty check also happens before the rear calculation, avoiding a negative remainder when there are no live items.
Follow a Complete Wraparound
Take capacity three. After inserting 10, 20, and 30, the physical slots are [10, 20, 30], the head is zero, and the size is three. The logical order is also 10, 20, 30. Another insertion is rejected because the queue is full.
Removing once advances the head to one and reduces the size to two. The remaining queue is 20, 30. Nothing needs to move in the array, and the old 10 may still be present in its now‑unused slot.
Insert 40 next. The destination is (1 + 2) % 3, which is zero. Physical storage becomes [40, 20, 30], but the logical queue is 20, 30, 40. Front() returns 20 and Rear() returns 40. Reading the array from index zero would give the wrong order; the head is part of the representation.
If we remove all three items, the queue becomes empty again. A later insertion still works from the current head. Capacity one follows exactly the same rules: every wrapped index is zero, and the count tells us whether that single slot is available.
What the Constant‑Time Claim Includes
Constructing this version fills an array of k slots, taking O(k) time and space. Each subsequent operation performs a fixed number of comparisons, indexed accesses, and arithmetic steps, giving O(1) time under the ordinary array‑access model. There is no growing array, copied suffix, or search for a free position.
The old numeric value remains in a removed slot until another insertion overwrites it. It is outside the logical queue and cannot be returned through the public methods. If adapting the structure to hold large objects, I would clear removed references so unused slots don't keep those objects alive. That is a different concern from maintaining queue order.
This version rejects new arrivals when full. Some ring buffers instead overwrite the oldest item, which can suit a recent‑history display, but that policy would fail this problem. Fixed capacity also doesn't make a queue safe for concurrent producers and consumers; coordinating shared access requires a separate design.
Test the Sequence, Not Just the Methods
A single successful insertion tells us very little about a reusable structure. I check complete operation sequences against an ordinary array model, including repeated fill‑and‑drain cycles, rejected insertions, rejected removals, zero values, and duplicate values. After each short‑sequence operation, the front, rear, empty flag, and full flag must agree.
The exhaustive checks cover all sequences through seven mutations drawn from inserting zero, inserting one, and removing, at capacities one, two, and three. Seeded longer sequences add more values. A capacity‑1,000 case performs 2,990 mutations plus eight observation calls, staying within the challenge's operation limit whilst forcing substantial wraparound.
My stateful data structures lab includes the exact implementation, the array reference, and an editable operation trace. Change the capacity to one or remove the full check, then see which next operation exposes the mistake. The tests also check that failed mutations leave the entire stored state unchanged.
Keep the Representation Small
As in my LRU cache article, choosing the right stored state makes each operation easier to explain. Here, the array holds values, the head establishes their order, and the size distinguishes occupied slots from available ones.
Once those responsibilities are separate, wraparound is just indexing. The interesting work is keeping the same meaning after every successful operation, every rejected operation, and every trip around the array.
Downloadable Resource
Stateful Data Structures Lab
Use my TypeScript lab to follow circular‑queue wraparound and a bounded min‑heap across complete operation sequences. Compare both structures with independent array and sorted references, inspect their internal state, and experiment with rejected queue operations, duplicate ranks, and heap repairs.