15% off all plans & roadmaps Use code

See plans

Design Circular Deque

Updated

TL;DR: Store the deque in a fixed array and keep a front index plus a count. Both ends move with modulo arithmetic, so no element ever shifts and every operation takes O(1) time.

Problem

Build a circular double-ended queue (deque). Implement the MyCircularDeque class with the methods below.

  • MyCircularDeque(int k) creates a deque with a maximum size of k.
  • boolean insertFront(int value) adds an item at the front. Returns true on success and false otherwise.
  • boolean insertLast(int value) adds an item at the rear. Returns true on success and false otherwise.
  • boolean deleteFront() removes an item from the front. Returns true on success and false otherwise.
  • boolean deleteLast() removes an item from the rear. Returns true on success and false otherwise.
  • int getFront() returns the front item. Returns -1 if the deque is empty.
  • int getRear() returns the last item. Returns -1 if the deque is empty.
  • boolean isEmpty() returns true if the deque is empty, and false otherwise.
  • boolean isFull() returns true if the deque is full, and false otherwise.

Example 1

Input: ["MyCircularDeque", "insertLast", "insertLast", "insertFront", "insertFront", "getRear", "isFull", "deleteLast", "insertFront", "getFront"]
[[3], [1], [2], [3], [4], [], [], [], [4], []]
Output: [null, true, true, true, false, 2, true, true, true, 4]
Explanation:
MyCircularDeque myCircularDeque = new MyCircularDeque(3);
myCircularDeque.insertLast(1);  // return True
myCircularDeque.insertLast(2);  // return True
myCircularDeque.insertFront(3); // return True
myCircularDeque.insertFront(4); // return False, the queue is full.
myCircularDeque.getRear();      // return 2
myCircularDeque.isFull();       // return True
myCircularDeque.deleteLast();   // return True
myCircularDeque.insertFront(4); // return True
myCircularDeque.getFront();     // return 4

Constraints

  • 1 <= k <= 1000
  • 0 <= value <= 1000
  • At most 2000 calls will be made to insertFront, insertLast, deleteFront, deleteLast, getFront, getRear, isEmpty, isFull.

Constraints that matter

  • Values go up to 1000 and k up to 1000, so storing the values in a fixed array of size k is cheap. The deque never needs more than k slots.
  • At most 2000 calls are made. An O(k) shift on every call costs up to about 2 * 10^6 steps, which is fast enough, but the problem is testing whether each operation is O(1).
  • The sentinel for an empty deque is -1, and 0 is a valid value. Emptiness must be checked with a size or count, never by comparing the returned value to -1.
  • Full and empty must be told apart. Two indices alone cannot do that when they meet, so the design needs a count or an extra slot.

View on LeetCode

Hints

Hint 1

This is a design problem.

Hint 2

Keep the elements in a growable array in order, with the front at index 0.

Solution

Intuition

This is a design problem. You build a class whose methods must keep one piece of state correct across many calls, so the first job is to choose that state. The deque needs constant-time access at both ends, and a plain array only gives that at one end.

The insight is that both ends can move while the stored values stay put. Keep a front index and a count. The rear is always front plus count, measured around the array. Modulo arithmetic wraps the indices, so the array behaves as a ring. This is the ring buffer pattern, also called a circular array.

Each stored value keeps its slot until it is deleted. Moving the front by one slot changes which slot is first, not where the other values live. The count separates full from empty, which two indices cannot do alone.

Watch the pattern animation

Worked example

Input: commands: ["MyCircularDeque", "deleteFront", "getFront", "getRear", "isEmpty", "isFull"], args: [[2], [], [], [], [], []]
Output: [null, false, -1, -1, true, false]
Explanation: The deque is created with k = 2 and stays empty. deleteFront returns false because there is nothing to remove. getFront and getRear both return -1 for an empty deque. isEmpty returns true. isFull returns false because 0 stored items is not equal to 2.

Approach 1: Brute force with array shifting

Keep the elements in a growable array in order, with the front at index 0. insertLast and deleteLast touch the end of the array, which is cheap. insertFront must place a new value at index 0, so every stored element moves one slot right. deleteFront has the mirror problem, because every element moves one slot left.

This is the direct solution, and it is correct. Nothing wraps, so no index arithmetic is needed. The cost is the shifting, which repeats on every front operation even though the stored values never change.

Steps

  1. In the constructor, store k and create an empty array.
  2. In insertFront and insertLast, return false when the array length equals k.
  3. insertFront inserts the value at index 0. insertLast appends it.
  4. deleteFront removes index 0 and shifts the rest left. deleteLast removes the last item.
  5. getFront reads index 0 and getRear reads the last index. Both return -1 when the array is empty.
  6. isEmpty checks for length 0. isFull checks for length equal to k.

Dry run

The example makes no successful inserts, so the array stays empty. Start with items = [] and capacity 2.

  1. deleteFront sees an empty array and returns false.
  2. getFront and getRear both return -1.
  3. isEmpty returns true.
  4. isFull compares length 0 with 2 and returns false.

The returned values are [null, false, -1, -1, true, false], which matches the expected output.

Complexity

TimeO(k) per front operation, O(1) for the end operations
SpaceO(k)

Let n be the number of stored elements, which never exceeds k. insertFront and deleteFront shift every stored element, so they do up to n moves, which is O(k). The other six methods do a fixed amount of work, such as one append, one length check or one index read, so each is O(1). The array holds at most k items, so the space is O(k).

PythonTested in our runner

from typing import List, Optional

class MyCircularDeque:
    def __init__(self, k: int):
        self.capacity = k
        self.items = []  # front at index 0

    def insertFront(self, value: int) -> bool:
        if self.isFull():
            return False
        self.items.insert(0, value)  # shifts every element right
        return True

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

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

    def deleteLast(self) -> bool:
        if self.isEmpty():
            return False
        self.items.pop()
        return True

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

    def getRear(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: Ring buffer with front index and countOptimalDesign (General/Specific)

What's slow: the shifting. Every insertFront or deleteFront moves all stored values, even though the values never need to move. The shifts are wasted work caused by tying the front to index 0.

The insight that fixes it: let the front be a moving index into a fixed array of size k. Moving the front one slot is a single index update, and modulo wraps it past the end. The rear is the slot after the last element, at (front + count) % k. A count tells you full from empty, so you never need a spare pointer comparison.

Steps

  1. Allocate a fixed array buffer of length k. Set front = 0 and count = 0.
  2. insertFront returns false if full. Otherwise it sets front = (front - 1 + k) % k, writes the value there, and increases count.
  3. insertLast returns false if full. Otherwise it writes to (front + count) % k, the first free slot after the last element, and increases count.
  4. deleteFront returns false if empty. Otherwise it sets front = (front + 1) % k and decreases count.
  5. deleteLast returns false if empty. Otherwise it decreases count, which frees the last slot for the next insert.
  6. getFront returns buffer[front]. getRear returns buffer[(front + count - 1) % k]. Both return -1 when empty.
  7. isEmpty checks count == 0. isFull checks count == k.

Dry run

Run the example with capacity k = 2. The table shows the state after each call.

StepCallfrontcountbufferReturns
0constructor(2)00[_, _]null
1deleteFront()00[_, _]false
2getFront()00[_, _]-1
3getRear()00[_, _]-1
4isEmpty()00[_, _]true
5isFull()00[_, _]false

The Returns column reads [null, false, -1, -1, true, false], which matches the expected output.

The example never fills the deque, so here is a wrap-around trace on a fresh k = 2 deque.

CallfrontcountbufferReturns
insertLast(1)01[1, _]true
insertFront(7)12[1, 7]true
insertLast(3)12[1, 7]false
getRear()12[1, 7]1
deleteFront()01[1, 7]true
getFront()01[1, 7]1

For insertFront(7), the new front is (0 - 1 + 2) % 2 = 1, so the value lands after the wrap. The deque holds [7, 1] and then [1].

Complexity

TimeO(1) per operation
SpaceO(k)

Let k be the capacity. Each method runs a fixed number of arithmetic operations and at most one array read or write. There are no loops or recursive calls, so each call is O(1), and m calls cost O(m). The array has k slots and the object stores three more integers, so the space is O(k).

PythonTested in our runner

from typing import List, Optional

class MyCircularDeque:
    def __init__(self, k: int):
        self.capacity = k
        self.buffer = [0] * k
        self.front = 0  # physical index of the front element
        self.count = 0  # number of stored elements

    def insertFront(self, value: int) -> bool:
        if self.isFull():
            return False
        # Python's % never returns a negative result for a positive divisor
        self.front = (self.front - 1) % self.capacity
        self.buffer[self.front] = value
        self.count += 1
        return True

    def insertLast(self, value: int) -> bool:
        if self.isFull():
            return False
        # The next free slot sits right after the last element
        self.buffer[(self.front + self.count) % self.capacity] = value
        self.count += 1
        return True

    def deleteFront(self) -> bool:
        if self.isEmpty():
            return False
        self.front = (self.front + 1) % self.capacity
        self.count -= 1
        return True

    def deleteLast(self) -> bool:
        if self.isEmpty():
            return False
        self.count -= 1  # the freed slot is reused by the next insert
        return True

    def getFront(self) -> int:
        if self.isEmpty():
            return -1
        return self.buffer[self.front]

    def getRear(self) -> int:
        if self.isEmpty():
            return -1
        return self.buffer[(self.front + self.count - 1) % self.capacity]

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

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

Common mistakes

  • front = front - 1 written without the + capacity in Java, C++, C#, JavaScript or Go. Those languages keep the sign of the left operand, so the index can become -1. Write (front - 1 + capacity) % capacity instead.
  • if (front == rear) used as the empty test. When the deque is full, the rear wraps onto the front as well. Track count and test count == 0 and count == capacity.
  • return buffer[rear] in getRear when rear points at the next free slot. The last stored value sits one slot earlier. Read (front + count - 1) % capacity instead.
  • Writing to the buffer before the isFull check. A write into a full deque overwrites the front value. Return false first, then write.
  • Decrementing count in deleteFront or deleteLast without the isEmpty guard. The count drops below zero, so isEmpty and isFull return wrong answers for the rest of the calls. Check emptiness first.
  • Using front after deleteFront when the deque becomes empty and then inserting from the wrong slot. An insert always writes to (front + count) % capacity for insertLast or front - 1 for insertFront, so the wrong formula here shows up as a corrupted buffer. Keep both formulas written exactly as the design defines them.

Edge cases

  • k = 1: insertFront and insertLast each succeed once. A second insert returns false, and getFront and getRear return the same value.
  • Empty deque: deleteFront and deleteLast return false, getFront and getRear return -1, isEmpty returns true, and isFull returns false when k is greater than 0.
  • A stored value of 0: getFront returns 0 and isEmpty stays false. The -1 sentinel must never be used as the emptiness test.
  • Full deque, then deleteLast, then insertLast: the new value takes the slot just freed, and isFull is true again.
  • Many calls that cycle the front far past k: the indices always stay between 0 and k - 1, because every move uses modulo.
  • Full deque with insertFront: returns false, and getRear and getFront both keep their previous values.

Follow-ups interviewers ask

Follow-ups are part of Pro

The questions interviewers ask after you solve Design Circular Deque, with how to answer them.

Unlock the follow-ups

Design Circular Deque FAQ

What is the time complexity of Design Circular Deque?

With the ring buffer, every operation runs in O(1) time. Each call does a fixed amount of index arithmetic and at most one array access. The space is O(k) for the array of capacity k.

Why use a ring buffer for Design Circular Deque?

Both ends need constant-time updates, and a plain array only gives that at one end. A ring buffer moves a front index and wraps it with modulo, so no stored value is ever copied. The count also tells full from empty.

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

Yes, beyond the array that holds the values. The k-slot array is required because the deque may hold k values at once. The remaining state is front, count and capacity, which is O(1). The shifting version also uses O(1) extra space, but it costs O(k) time per front operation.

Why is the modulo step different in Python?

Python's % returns a result with the sign of the divisor, so (front - 1) % capacity is already in range. Java, C++, C#, JavaScript and Go keep the sign of the left operand, so you must add capacity before taking the modulo.

Asked at

See which companies ask this — Pro

Practise it