Circular Array (Ring Buffer)

Design Circular Queue

Medium
Solve it on LeetCode ↗

The problem

Implement a fixed-capacity circular queue: enQueue, deQueue, Front, Rear, isEmpty, isFull — all O(1).

Stuck? Reveal hints one at a time

How to approach it

  1. 1Allocate an array of size k; keep head = 0 and count = 0.
  2. 2enQueue: if full, false; else write at (head + count) % k and increment count.
  3. 3deQueue: if empty, false; else advance head = (head + 1) % k and decrement count.
  4. 4Front reads at head; Rear reads at (head + count − 1) % k.

Key insight

head+count fully determines the queue — storing a separate tail invites drift bugs, and count makes isFull/isEmpty trivial instead of ambiguous.

The solution

Watch out for

  • Rear is at head+count−1, not at a stored tail pointer — deriving beats maintaining.
  • Without a count you must waste one slot or add a flag to tell full from empty.