Design Circular Deque

Medium

Topics
ArrayQueueDesign

Design a circular double-ended queue. Implement MyCircularDeque(k) and: insertFront(value), insertLast(value), deleteFront(), deleteLast() (each returns true on success), getFront() and getRear() (return the value or -1 if empty), isEmpty(), and isFull().

Example 1

returnsMyCircularDeque(3)insertLast(1)trueinsertLast(2)trueinsertFront(3)trueinsertFront(4)falsegetRear()2isFull()truedeleteLast()trueinsertFront(4)truegetFront()4
The circular queue with both ends live. Inserting at the front means stepping head backwards with (head - 1 + cap) % cap — the + cap matters, because a bare negative modulo is not an index.
Calls run top to bottom; the arrow shows what each one returns.
Input:  operations = ["MyCircularDeque","insertLast","insertLast","insertFront","insertFront","getRear","isFull","deleteLast","insertFront","getFront"], values = [[3],[1],[2],[3],[4],[],[],[],[4],[]]
Output: [null,true,true,true,false,2,true,true,true,4]

Constraints

  • 1 <= k <= 1000
  • 0 <= value <= 1000
  • At most 2000 calls.
Editorial — intuition, approach, complexity and pitfalls

Intuition

A deque supports insert/delete at both ends. Back it with a fixed array and track a head index and a size; the front grows by moving head backward (modulo), the rear grows forward.

Approach

  1. Keep an array of capacity k, a head index, and a count.
  2. insertFront moves head back by one (modulo) and writes; insertLast writes at (head + count) % k.
  3. deleteFront advances head; deleteLast just drops the count; getFront/getRear read the ends or return -1.

Dry Run

MyCircularDeque(3). Same buffer-plus-head-plus-count state as the circular queue,
but now the head can move in both directions.
  insertLast 1    -> true    buf [1, 0, 0]   head 0  count 1
  insertLast 2    -> true    buf [1, 2, 0]   head 0  count 2
  insertFront 3   -> true    buf [1, 2, 3]   head 2  count 3
                             head moved BACKWARDS from 0 to 2
  insertFront 4   -> false   full
  getRear         -> 2       index (2 + 3 - 1) % 3 = 1
  isFull          -> true
  deleteLast      -> true    count 2; nothing is erased, the slot is just unowned
  insertFront 4   -> true    buf [1, 4, 3]   head 1  count 3
  getFront        -> 4
answer null|true|true|true|false|2|true|true|true|4
insertFront is the operation that distinguishes this from a circular queue, and
`(head - 1) % cap` is how it wraps -- in Python that maps 0 to 2 directly. In Java
or C++ the modulo of a negative is negative, so it has to be written
(head - 1 + cap) % cap.
deleteLast only decrements the count. The value stays in the buffer and is simply
no longer addressable, which is why the trace shows buf unchanged across that
step and then the 2 being overwritten later.
Everything else is derived rather than stored: the rear is at
(head + count - 1) % cap and the next back-insertion point at (head + count) % cap.
Keeping a separate tail index would mean two things to update on every one of the
four mutating operations.

Complexity

  • Time — O(1): both ends update in constant time via modular indexing.
  • Space — O(k): the fixed backing array.

Common Pitfalls

  • Python’s % keeps head in range on decrement; in C++/Java add cap before taking the modulo to avoid negatives.

Full Solution — all languages

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

    def insertFront(self, value):
        if self.isFull():
            return False
        self.head = (self.head - 1) % self.cap
        self.buf[self.head] = value
        self.count += 1
        return True

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

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

    def deleteLast(self):
        if self.isEmpty():
            return False
        self.count -= 1
        return True

    def getFront(self):
        return -1 if self.isEmpty() else self.buf[self.head]

    def getRear(self):
        return -1 if self.isEmpty() else self.buf[(self.head + self.count - 1) % self.cap]

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

    def isFull(self):
        return self.count == self.cap
Asked at Snowflake
SensAI
Beta
Tap the mic to stop voice mode