Design Circular Queue

Medium JavaDesignQueueArray

Problem

Design a fixed-capacity circular queue MyCircularQueue(int k) with enQueue, deQueue, Front, Rear, isEmpty, isFull. Each returns the expected primitive (boolean or int — -1 for Front/Rear when empty).

Example 1 Input: k=3; enQ(1); enQ(2); enQ(3); enQ(4) Output: false (full)

Constraints

Approach — Core Patterns

This is a Core Patterns problem. The idea: pick the data structure best matched to the constraints and solve it in one clean pass. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.

Complexity: see the walkthrough below.

Solution code

Python

class MyCircularQueue:
    def __init__(self, k):
        self.q = [0] * k
        self.cap = k
        self.head = 0
        self.count = 0

    def enQueue(self, value):
        if self.count == self.cap:
            return False
        self.q[(self.head + self.count) % self.cap] = value
        self.count += 1
        return True

    def deQueue(self):
        if self.count == 0:
            return False
        self.head = (self.head + 1) % self.cap
        self.count -= 1
        return True

    def Front(self):
        return -1 if self.count == 0 else self.q[self.head]

    def Rear(self):
        return -1 if self.count == 0 else self.q[(self.head + self.count - 1) % self.cap]

    def isEmpty(self):
        return self.count == 0

    def isFull(self):
        return self.count == self.cap

Java

class MyCircularQueue {
    private int[] buf;
    private int head = 0, tail = -1, size = 0;
    public MyCircularQueue(int k) { buf = new int[k]; }
    public boolean enQueue(int value) {
        if (size == buf.length) return false;
        tail = (tail + 1) % buf.length;
        buf[tail] = value;
        size++;
        return true;
    }
    public boolean deQueue() {
        if (size == 0) return false;
        head = (head + 1) % buf.length;
        size--;
        return true;
    }
    public int Front() { return size == 0 ? -1 : buf[head]; }
    public int Rear()  { return size == 0 ? -1 : buf[tail]; }
    public boolean isEmpty() { return size == 0; }
    public boolean isFull()  { return size == buf.length; }
}

class Solution {}

Practice it

Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.

Solve Design Circular Queue interactively → ← All solutions