Implement a fixed-capacity queue with circular array indices.
Use the editor below to process circular-queue operations.
Keep items in place
Use a fixed-capacity array without shifting existing values. Track the front position and current size. Handle empty, full, capacity-one, and wraparound states.
Submit your implementation when it passes the examples.
Process operations on a fixed-capacity circular queue without shifting existing items.
Return one output per operation. The constructor produces null; enqueue and dequeue return booleans; Front, Rear, isEmpty, and isFull return their values.
1 ≤ capacity ≤ 1,000Results appear here after a run.
The front index identifies the next item to remove. With capacity k and room available, insert at (front + size) % k. When at least one item is present, read the rear at (front + size - 1) % k. A dequeue advances front by one modulo k and reduces size.
With capacity 3, enqueue 1, 2, 3, dequeue 1, then enqueue 4. The physical slots read [4, 2, 3], but front is 1, so the queue reads 2, 3, 4. Its front is 2 and its rear is 4.
function runCircularQueue(operations, values) {
class MyCircularQueue {
constructor(capacity) {
this.items = Array(capacity);
this.capacity = capacity;
this.frontIndex = 0;
this.size = 0;
}
enQueue(value) {
if (this.isFull()) return false;
const rearIndex = (this.frontIndex + this.size) % this.capacity;
this.items[rearIndex] = value;
this.size++;
return true;
}
deQueue() {
if (this.isEmpty()) return false;
this.frontIndex = (this.frontIndex + 1) % this.capacity;
this.size--;
return true;
}
Front() {
return this.isEmpty() ? -1 : this.items[this.frontIndex];
}
Rear() {
if (this.isEmpty()) return -1;
const rearIndex =
(this.frontIndex + this.size - 1) % this.capacity;
return this.items[rearIndex];
}
isEmpty() {
return this.size === 0;
}
isFull() {
return this.size === this.capacity;
}
}
let queue;
const output = [];
for (let index = 0; index < operations.length; index++) {
const operation = operations[index];
if (operation === "MyCircularQueue") {
queue = new MyCircularQueue(values[index][0]);
output.push(null);
} else if (operation === "enQueue") {
output.push(queue.enQueue(values[index][0]));
} else {
output.push(queue[operation]());
}
}
return output;
}| Measure | Complexity | Explanation |
|---|---|---|
| Time | O(k + n) | Initialize k slots, then perform n constant-time queue operations. |
| Auxiliary space | O(k) | The fixed array stores exactly the queue capacity k. |