Circular / Bounded Queue

Design Circular Deque

Medium
Solve it on LeetCode ↗

The problem

Implement a fixed-capacity double-ended queue over a circular buffer: insert/delete at both ends, read both ends, isEmpty, isFull — all O(1).

Stuck? Reveal hints one at a time

How to approach it

  1. 1Array of size k, head = 0, count = 0.
  2. 2insertFront: head = (head − 1 + k) % k, write there, count++.
  3. 3insertLast: write at (head + count) % k, count++.
  4. 4deleteFront: head = (head + 1) % k, count−−. deleteLast: count−−.
  5. 5Front reads head; Rear reads (head + count − 1) % k.

Key insight

A deque over a ring is just a queue whose head may also retreat — adding k before the modulo keeps every index non-negative in languages where % can return negatives.

The solution

Watch out for

  • JS % returns negatives for negative operands — always add k first.
  • deleteLast is just count−− because the rear is derived, not stored.