Design Circular Queue easy
Description
Design your implementation of a circular queue. Implement the MyCircularQueue class:
MyCircularQueue(k)— initialize the queue with capacityk.enQueue(value)— insert an element. Returnstrueon success,falseif full.deQueue()— delete the element from the front. Returnstrueon success,falseif empty.Front()— return the front element, or-1if empty.Rear()— return the last element, or-1if 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() # 4Constraints
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 capacityThe classic gotcha is deciding empty vs full when both look like front == rear. Two standard fixes:
- Keep an explicit
count— cleanest. We use this. - 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.
Fill it up, dequeue from the front, then enqueue again — watch rear wrap to slot 0.
Code
Explanation
frontalways points to the current front element.rearpoints to the next empty slot, not to the last element. (That’s whyRear()reads from(rear - 1) % capacity.)countis 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 capacityk.