15% off all plans & roadmaps Use code

See plans

Design Circular Queue

Updated

TL;DR: Build a fixed-size ring buffer that keeps a head index and an item count, so every operation runs in O(1) time. A plain list shifts every item on each dequeue, which does work the queue never needs.

Problem

Design a circular queue. A circular queue is a linear data structure that follows first in, first out (FIFO) order. Its last position connects back to its first position, which forms a circle. People also call it a Ring Buffer.

The main benefit is reuse. In a normal queue, once the back reaches the end of the storage, you cannot insert a value even when the slots at the front are empty. A circular queue wraps around and uses those slots.

Implement the MyCircularQueue class:

  • MyCircularQueue(k) initializes the queue with size k.
  • int Front() returns the front item. If the queue is empty, return -1.
  • int Rear() returns the last item. If the queue is empty, return -1.
  • boolean enQueue(int value) inserts an element. Return true if the operation succeeds.
  • boolean deQueue() removes an element. Return true if the operation succeeds.
  • boolean isEmpty() checks whether the queue is empty.
  • boolean isFull() checks whether the queue is full.

You must solve the problem without the built-in queue data structure of your language.

Example 1

Input: ["MyCircularQueue", "enQueue", "enQueue", "enQueue", "enQueue", "Rear", "isFull", "deQueue", "enQueue", "Rear"]
[[3], [1], [2], [3], [4], [], [], [], [4], []]
Output: [null, true, true, true, false, 3, true, true, true, 4]
Explanation:
MyCircularQueue myCircularQueue = new MyCircularQueue(3);
myCircularQueue.enQueue(1); // return True
myCircularQueue.enQueue(2); // return True
myCircularQueue.enQueue(3); // return True
myCircularQueue.enQueue(4); // return False
myCircularQueue.Rear(); // return 3
myCircularQueue.isFull(); // return True
myCircularQueue.deQueue(); // return True
myCircularQueue.enQueue(4); // return True
myCircularQueue.Rear(); // return 4

Constraints

  • 1 <= k <= 1000
  • 0 <= value <= 1000
  • At most 3000 calls will be made to enQueue, deQueue, Front, Rear, isEmpty, and isFull.

Constraints that matter

  • k is at least 1, so the modulo by k never divides by zero and the array always has a slot to write.
  • Values are never negative, so -1 is free to signal an empty queue from Front and Rear.
  • Up to 3000 calls means each call must do a small, fixed amount of work. A cost of O(k) per call would still pass, but the interview expects the O(1) bound.
  • Capacity is at most 1000, so the array can be allocated once in the constructor and never resized.

View on LeetCode

Hints

Hint 1

A circular queue needs two facts at every moment: where the front item sits, and how many items are stored.

Hint 2

A beginner usually stores the items in a plain list.

Solution

Intuition

A circular queue needs two facts at every moment: where the front item sits, and how many items are stored. The values live in a fixed array of k slots. Once you know the head index and the count, you can find every item and every free slot without moving anything.

This is a design problem built on index arithmetic, usually called a ring buffer. The array has k slots, but the queue must keep accepting values after the end of the array. Taking an index modulo k sends it back to the start, so the array behaves like a circle.

Why track a count instead of comparing head and tail? When head equals tail, the queue could be empty or full, and both states look the same. A count separates the two cases. The tail index never needs storage, because it is always (head + count) mod k.

Take k = 3. enQueue(1), enQueue(2), and enQueue(3) fill slots 0, 1, and 2, and head stays at 0. deQueue moves head to 1 and drops count to 2. enQueue(4) writes to slot (1 + 2) mod 3, which is slot 0, the slot freed at the front. Count is now 3, so Rear reads slot (1 + 3 - 1) mod 3, which is slot 0 and holds 4.

Watch the pattern animation

Worked example

Input: commands = ["MyCircularQueue", "Front", "Rear", "isEmpty", "isFull", "deQueue"]
arguments = [[2], [], [], [], [], []]
Output: [null, -1, -1, true, false, false]
Explanation: The queue has capacity 2 and starts empty. Front and Rear return -1 because nothing is stored. isEmpty returns true. isFull returns false because the count is 0, not 2. deQueue returns false because there is nothing to remove.

Approach 1: Brute force with a plain list

A beginner usually stores the items in a plain list. enQueue appends to the end, and deQueue removes the first element. The list keeps the items in order, so every answer is correct. The cost sits in deQueue, which removes index 0. Every remaining item shifts one slot left, so each dequeue does work that grows with the number of items stored.

Steps

  1. Create an empty list and store the capacity k.
  2. In enQueue, return false if the list already holds k items. Otherwise append the value and return true.
  3. In deQueue, return false if the list is empty. Otherwise remove index 0 and return true.
  4. Front returns the first item, and Rear returns the last item. Both return -1 when the list is empty.
  5. isEmpty checks that the length is 0. isFull checks that the length equals k.

Dry run

Start with k = 2 and the list []. Front returns -1 because the list is empty. Rear returns -1 for the same reason. isEmpty returns true. isFull compares the length 0 with 2 and returns false. deQueue sees an empty list and returns false. The outputs are [null, -1, -1, true, false, false], which matches the example.

Complexity

TimeO(k) per deQueue, O(1) for the other operations
SpaceO(k)

Let n be the number of items stored, where n is at most k. Removing index 0 moves the other n - 1 items one slot left, so deQueue does O(n) work, which is O(k) in the worst case. enQueue, Front, Rear, isEmpty, and isFull touch one slot or read a length, so each does constant work. The list never holds more than k items, so the space is O(k).

PythonTested in our runner

from typing import List, Optional

class MyCircularQueue:
    def __init__(self, k: int):
        self.capacity = k
        self.items = []

    def enQueue(self, value: int) -> bool:
        if self.isFull():
            return False
        self.items.append(value)
        return True

    def deQueue(self) -> bool:
        if self.isEmpty():
            return False
        self.items.pop(0)  # shifts every remaining item left
        return True

    def Front(self) -> int:
        if self.isEmpty():
            return -1
        return self.items[0]

    def Rear(self) -> int:
        if self.isEmpty():
            return -1
        return self.items[-1]

    def isEmpty(self) -> bool:
        return len(self.items) == 0

    def isFull(self) -> bool:
        return len(self.items) == self.capacity

The Design (General/Specific) infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

Design (General/Specific)

Part of Design Patterns

Approach 2: Fixed array with head and count (ring buffer)OptimalDesign (General/Specific)

What's slow: deQueue shifts every item, even though only the front position changed. The insight that fixes it: leave the items where they are and move a head index forward. New values go to slot (head + count) mod k, so a slot freed at the front gets reused once the tail wraps around to it. The count tells you when the array is full or empty.

Steps

  1. Allocate an array of k slots. Set head to 0 and count to 0.
  2. isEmpty returns count == 0. isFull returns count == k.
  3. enQueue: if the queue is full, return false. Otherwise compute tail = (head + count) mod k, write the value there, increase count by 1, and return true.
  4. deQueue: if the queue is empty, return false. Otherwise set head = (head + 1) mod k, decrease count by 1, and return true.
  5. Front returns data[head]. Rear returns data[(head + count - 1) mod k]. Both return -1 when the queue is empty.

Dry run

The table traces the statement example from the Example section above, with k = 2.

StepCallReturnsheadcountdata
0MyCircularQueue(2)null00[0, 0]
1Front()-100[0, 0]
2Rear()-100[0, 0]
3isEmpty()true00[0, 0]
4isFull()false00[0, 0]
5deQueue()false00[0, 0]

The outputs are [null, -1, -1, true, false, false]. The last call returns false because count is 0, so nothing changes.

Complexity

TimeO(1) per operation
SpaceO(k)

Let k be the capacity. Each method runs a fixed number of comparisons, arithmetic steps, and at most one array access, so each costs O(1). The constructor allocates k slots, and the array never grows, so the space is O(k). The total work for m calls is O(m), because no call touches the rest of the array.

PythonTested in our runner

from typing import List, Optional

class MyCircularQueue:
    def __init__(self, k: int):
        self.capacity = k
        self.data = [0] * k
        self.head = 0
        self.count = 0

    def enQueue(self, value: int) -> bool:
        if self.isFull():
            return False
        # the next free slot is head + count, wrapped by modulo
        self.data[(self.head + self.count) % self.capacity] = value
        self.count += 1
        return True

    def deQueue(self) -> bool:
        if self.isEmpty():
            return False
        # only the front moves, no items are copied
        self.head = (self.head + 1) % self.capacity
        self.count -= 1
        return True

    def Front(self) -> int:
        if self.isEmpty():
            return -1
        return self.data[self.head]

    def Rear(self) -> int:
        if self.isEmpty():
            return -1
        # the last item sits one slot before the next free slot
        return self.data[(self.head + self.count - 1) % self.capacity]

    def isEmpty(self) -> bool:
        return self.count == 0

    def isFull(self) -> bool:
        return self.count == self.capacity

Common mistakes

  • Rear returning data[(head + count) % k]. That slot is the next free position, not the last item. Use (head + count - 1) % k so Rear reads the newest value.
  • head = head + 1 in deQueue with no modulo. After the last slot, head reaches k and Front reads past the end of the array. Use (head + 1) % k.
  • if (head == tail) as the only empty or full test. Both states produce the same indices. Track a count, or leave one slot empty and test (tail + 1) % k == head for full.
  • Writing before the full check, such as data[tail] = value followed by if isFull(). When the queue is full, the write overwrites the front item. Check fullness first, then write.
  • return data[head] in Front with no empty check. After the last deQueue, the slot still holds an old value, so Front returns a stale number instead of -1. Check count == 0 first.

Edge cases

  • k = 1: the first enQueue succeeds, the second returns false, and modulo by 1 always gives slot 0. After deQueue, enQueue works again.
  • Empty queue: Front and Rear return -1, deQueue returns false, isEmpty returns true, and isFull returns false.
  • Value 0: 0 is a valid stored value, so Front returning 0 is correct. Decide emptiness from count, never from the returned value.
  • Full queue: enQueue returns false and leaves every slot unchanged. Rear still returns the most recent value that was accepted.
  • Repeated fill and drain across the array end with k = 3: head cycles 0, 1, 2, 0, and every value comes out in insertion order.
  • Maximum load with k = 1000 and 3000 calls: indices stay between 0 and k - 1, and no call reads outside the array.

Follow-ups interviewers ask

What if the queue should grow when it is full instead of rejecting values?
Allocate an array of twice the size, copy the items in order starting from head, then set head to 0. Each copy costs O(k), but doubling means the copies happen rarely. The amortized cost of enQueue stays O(1). This also removes the fixed capacity, so isFull would no longer be needed.
Can you drop the count variable and still tell full from empty?
Yes. Keep head and tail, and leave one slot always empty. The queue is empty when head equals tail, and full when (tail + 1) mod k equals head. The usable capacity drops to k - 1, so you would allocate k + 1 slots to store k items.
What if several threads call enQueue and deQueue at the same time?
A single lock around the methods makes each call atomic, and it is the simplest correct answer. A lock-free ring buffer exists for exactly one producer and one consumer. In that case the producer owns tail and the consumer owns head, and both indices are atomic.

Design Circular Queue FAQ

What is the time complexity of Design Circular Queue?

Every operation runs in O(1) time with the ring buffer, because each call does a fixed number of steps. The array size does not change the step count. The plain list version costs O(k) per deQueue because it shifts items.

Why use a ring buffer for Design Circular Queue?

The problem asks for FIFO order and reuse of slots freed at the front. A head index plus modulo arithmetic makes the array act like a circle, so a dequeue only moves the head. No item is copied, which keeps every call at O(1).

Can Design Circular Queue be solved in O(1) extra space?

Beyond the k slots that hold the values, the solution uses O(1) extra space for head and count. The k slots themselves are required, because the queue must store up to k values. So the total space is O(k), and that cannot be reduced.

Why does the solution need a count variable?

When head equals tail, the queue could be empty or full, and the indices alone cannot tell which. A count stores the answer directly. The tail index is then derived from head and count, so it does not need its own variable.

Is a linked list a valid alternative for Design Circular Queue?

Yes. A circular singly linked list with head, tail, and a size counter also gives O(1) operations. It allocates one node per value, though, so it uses more memory than the fixed array.

Asked at

See which companies ask this — Pro

Practise it