Ready — enter an integer to enqueue
Speed
🎨 Customize Colors
Scene Background
Element Color
Value Color
Pointer Color

🚥 Circular Queue

A Circular Queue (also known as a Ring Buffer) is a linear data structure where the last position is connected back to the first position to make a circle. This resolves the major limitation of a normal Queue where space is lost once an element is dequeued.

⏱ Access: O(n) ⏱ Search: O(n) ⏱ Enqueue: O(1) ⏱ Dequeue: O(1) 💾 Space: O(1)
Python
class CircularQueue:
    def __init__(self, k: int):
        self.k = k
        self.q = [None] * k
        self.head = self.tail = -1

    def enQueue(self, value: int) -> bool:
        if self.isFull(): return False
        if self.isEmpty(): self.head = 0
        self.tail = (self.tail + 1) % self.k
        self.q[self.tail] = value
        return True

    def deQueue(self) -> bool:
        if self.isEmpty(): return False
        if self.head == self.tail:
            self.head = self.tail = -1
        else:
            self.head = (self.head + 1) % self.k
        return True
JavaScript
class CircularQueue {
    constructor(k) {
        this.q = new Array(k);
        this.k = k;
        this.head = -1;
        this.tail = -1;
    }

    enQueue(value) {
        if (this.isFull()) return false;
        if (this.isEmpty()) this.head = 0;
        this.tail = (this.tail + 1) % this.k;
        this.q[this.tail] = value;
        return true;
    }

    deQueue() {
        if (this.isEmpty()) return false;
        if (this.head === this.tail) {
            this.head = this.tail = -1;
        } else {
            this.head = (this.head + 1) % this.k;
        }
        return true;
    }
}