KatInterview

860. Design Circular Queue

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to design a circular queue of a fixed size k. A circular queue, also known as a ring buffer, is a fixed-size queue where the last position is connected back to the first position, forming a circle. This structure allows us to reuse empty slots at the front of the queue, which is an advantage over a standard queue implemented with a simple array.

Solution

Design Circular Queue in Python

class MyCircularQueue:

    def __init__(self, k: int):
        # We use a list of size k+1 to easily distinguish
        # between empty and full states.
        self.capacity = k + 1
        self.data = [0] * self.capacity
        self.head = 0
        self.tail = 0

    def enQueue(self, value: int) -> bool:
        if self.isFull():
            return False
        # Place the new value at the tail position.
        self.data[self.tail] = value
        # Move tail pointer to the next position, wrapping around if necessary.
        self.tail = (self.tail + 1) % self.capacity
        return True

    def deQueue(self) -> bool:
        if self.isEmpty():
            return False
        # Move head pointer to the next position, effectively removing the front element.
        self.head = (self.head + 1) % self.capacity
        return True

    def Front(self) -> int:
        if self.isEmpty():
            return -1
        # The front element is at the head index.
        return self.data[self.head]

    def Rear(self) -> int:
        if self.isEmpty():
            return -1
        # The rear element is at the position just before tail.
        # This formula handles wrap-around cases where tail might be 0.
        rear_index = (self.tail - 1 + self.capacity) % self.capacity
        return self.data[rear_index]

    def isEmpty(self) -> bool:
        # If head and tail are at the same position, the queue is empty.
        return self.head == self.tail

    def isFull(self) -> bool:
        # If tail is one position behind head (circularly), the queue is full.
        # This is why we use one extra space in the list.
        return (self.tail + 1) % self.capacity == self.head


# Your MyCircularQueue object will be instantiated and called as such:
# obj = MyCircularQueue(k)
# param_1 = obj.enQueue(value)
# param_2 = obj.deQueue()
# param_3 = obj.Front()
# param_4 = obj.Rear()
# param_5 = obj.isEmpty()
# param_6 = obj.isFull()

Design Circular Queue in Java

class MyCircularQueue {
    private int[] data;
    private int head;
    private int tail;
    private int capacity;

    public MyCircularQueue(int k) {
        // Use an array of size k+1 for easier state management.
        capacity = k + 1;
        data = new int[capacity];
        head = 0;
        tail = 0;
    }
    
    public boolean enQueue(int value) {
        if (isFull()) {
            return false;
        }
        // Insert value at the tail position.
        data[tail] = value;
        // Move tail forward, wrapping around.
        tail = (tail + 1) % capacity;
        return true;
    }
    
    public boolean deQueue() {
        if (isEmpty()) {
            return false;
        }
        // Move head forward, "removing" the front element.
        head = (head + 1) % capacity;
        return true;
    }
    
    public int Front() {
        if (isEmpty()) {
            return -1;
        }
        // Front element is at the head index.
        return data[head];
    }
    
    public int Rear() {
        if (isEmpty()) {
            return -1;
        }
        // Rear element is at index before tail.
        // The formula (tail - 1 + capacity) % capacity handles wrap-around cases.
        int rearIndex = (tail - 1 + capacity) % capacity;
        return data[rearIndex];
    }
    
    public boolean isEmpty() {
        // Empty if head and tail pointers are the same.
        return head == tail;
    }
    
    public boolean isFull() {
        // Full if tail pointer is one step behind head pointer (circularly).
        return (tail + 1) % capacity == head;
    }
}

/**
 * Your MyCircularQueue object will be instantiated and called as such:
 * MyCircularQueue obj = new MyCircularQueue(k);
 * boolean param_1 = obj.enQueue(value);
 * boolean param_2 = obj.deQueue();
 * int param_3 = obj.Front();
 * int param_4 = obj.Rear();
 * boolean param_5 = obj.isEmpty();
 * boolean param_6 = obj.isFull();
 */

Design Circular Queue in C++

class MyCircularQueue {
private:
    std::vector<int> data;
    int head;
    int tail;
    int capacity;

public:
    MyCircularQueue(int k) {
        // We use an array of size k+1 to easily distinguish
        // between empty and full states.
        capacity = k + 1;
        data.resize(capacity);
        head = 0;
        tail = 0;
    }
    
    bool enQueue(int value) {
        if (isFull()) {
            return false;
        }
        // Place the new value at the tail position.
        data[tail] = value;
        // Move tail pointer to the next position, wrapping around if necessary.
        tail = (tail + 1) % capacity;
        return true;
    }
    
    bool deQueue() {
        if (isEmpty()) {
            return false;
        }
        // Move head pointer to the next position, effectively removing the front element.
        head = (head + 1) % capacity;
        return true;
    }
    
    int Front() {
        if (isEmpty()) {
            return -1;
        }
        // The front element is at the head index.
        return data[head];
    }
    
    int Rear() {
        if (isEmpty()) {
            return -1;
        }
        // The rear element is at the position just before tail.
        // We use (tail - 1 + capacity) % capacity to handle wrap-around cases
        // where tail might be 0.
        int rearIndex = (tail - 1 + capacity) % capacity;
        return data[rearIndex];
    }
    
    bool isEmpty() {
        // If head and tail are at the same position, the queue is empty.
        return head == tail;
    }
    
    bool isFull() {
        // If tail is one position behind head (circularly), the queue is full.
        // This is why we use one extra space in the array.
        return (tail + 1) % capacity == head;
    }
};

/**
 * Your MyCircularQueue object will be instantiated and called as such:
 * MyCircularQueue* obj = new MyCircularQueue(k);
 * bool param_1 = obj->enQueue(value);
 * bool param_2 = obj->deQueue();
 * int param_3 = obj->Front();
 * int param_4 = obj->Rear();
 * bool param_5 = obj->isEmpty();
 * bool param_6 = obj->isFull();
 */

Design Circular Queue in TypeScript

class MyCircularQueue {
    private data: number[];
    private head: number;
    private tail: number;
    private capacity: number;

    constructor(k: number) {
        // Use an array of size k+1 for easier state management.
        this.capacity = k + 1;
        this.data = new Array(this.capacity);
        this.head = 0;
        this.tail = 0;
    }

    enQueue(value: number): boolean {
        if (this.isFull()) {
            return false;
        }
        // Insert value at the tail position.
        this.data[this.tail] = value;
        // Move tail forward, wrapping around.
        this.tail = (this.tail + 1) % this.capacity;
        return true;
    }

    deQueue(): boolean {
        if (this.isEmpty()) {
            return false;
        }
        // Move head forward, "removing" the front element.
        this.head = (this.head + 1) % this.capacity;
        return true;
    }

    Front(): number {
        if (this.isEmpty()) {
            return -1;
        }
        // Front element is at the head index.
        return this.data[this.head];
    }

    Rear(): number {
        if (this.isEmpty()) {
            return -1;
        }
        // Rear element is at index before tail.
        // The formula (tail - 1 + capacity) % capacity handles wrap-around cases.
        const rearIndex = (this.tail - 1 + this.capacity) % this.capacity;
        return this.data[rearIndex];
    }

    isEmpty(): boolean {
        // Empty if head and tail pointers are the same.
        return this.head === this.tail;
    }

    isFull(): boolean {
        // Full if tail pointer is one step behind head pointer (circularly).
        return (this.tail + 1) % this.capacity === this.head;
    }
}

/**
 * Your MyCircularQueue object will be instantiated and called as such:
 * var obj = new MyCircularQueue(k)
 * var param_1 = obj.enQueue(value)
 * var param_2 = obj.deQueue()
 * var param_3 = obj.Front()
 * var param_4 = obj.Rear()
 * var param_5 = obj.isEmpty()
 * var param_6 = obj.isFull()
 */

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.