Design Circular Queue easy

Description

Design your implementation of a circular queue. Implement the MyCircularQueue class:

  • MyCircularQueue(k) — initialize the queue with capacity k.
  • enQueue(value) — insert an element. Returns true on success, false if full.
  • deQueue() — delete the element from the front. Returns true on success, false if empty.
  • Front() — return the front element, or -1 if empty.
  • Rear() — return the last element, or -1 if empty.
  • isEmpty() / isFull() — booleans.

All operations must be O(1).

Examples

q = MyCircularQueue(3)
q.enQueue(1)    # True
q.enQueue(2)    # True
q.enQueue(3)    # True
q.enQueue(4)    # False  (full)
q.Rear()        # 3
q.isFull()      # True
q.deQueue()     # True
q.enQueue(4)    # True   (slot freed by deQueue)
q.Rear()        # 4

Constraints

  • 1 <= k <= 1000
  • All operations are O(1).

Intuition

This is the Circular Queue from Basic Operations, boxed as a class. The whole trick lives in two formulas:

enqueue: rear  = (rear  + 1) mod capacity
dequeue: front = (front + 1) mod capacity

The classic gotcha is deciding empty vs full when both look like front == rear. Two standard fixes:

  1. Keep an explicit count — cleanest. We use this.
  2. Leave one slot perpetually empty — saves one int, costs one slot, easy to get wrong.

Play with it

Try it: Circular Queue
Watch how front and rear wrap around the ring with modular arithmetic.
[0][1][2][3][4]size0/5

Fill it up, dequeue from the front, then enqueue again — watch rear wrap to slot 0.

Code

Explanation

  • front always points to the current front element.
  • rear points to the next empty slot, not to the last element. (That’s why Rear() reads from (rear - 1) % capacity.)
  • count is the source of truth for emptiness and fullness — no aliasing problems.
⚠️

Watch the Rear() indexing. A common bug is reading data[rear] directly — but rear points to the next write location, which is empty. Subtract one and wrap.

Analysis

  • Time: O(1) for every operation.
  • Space: O(k) — one array of capacity k.