Data Structures & Algorithms Queues & Deques
💡
Exercise 79

Design Circular Queue 25 XP Medium

LeetCode Ctrl+Enter Run Ctrl+S Save

A Circular Queue uses a fixed-size array where the end wraps around to the beginning. When the queue is full, you can't add more — but when an element is removed from the front, that space becomes available at the end.

cq = MyCircularQueue(3) # capacity 3 cq.enQueue(1) # True [1, _, _] cq.enQueue(2) # True [1, 2, _] cq.enQueue(3) # True [1, 2, 3] — full! cq.enQueue(4) # False — can't add, it's full cq.Rear() # 3 cq.isFull() # True cq.deQueue() # True [_, 2, 3] cq.enQueue(4) # True [4, 2, 3] — wraps around!

Key idea: Use two pointershead and tail — with modular arithmetic:

  • head: Index of front element
  • tail: Index where next enqueue goes
  • Wrap around: (index + 1) % capacity
  • Track count to distinguish full vs empty
📋 Instructions
Implement a circular queue with the given operations. Test the enQueue, deQueue, Front, Rear, isEmpty, and isFull operations.
Use a list of fixed size, head pointer, and count. enQueue: place at (head+count)%k, increment count. deQueue: increment head = (head+1)%k, decrement count. Front: data[head]. Rear: data[(head+count-1)%k].
🧪 Test Cases
Input
cq.enQueue(1)
Expected
True
Boolean check
Input
cq.enQueue(2)
Expected
True
Boolean check
Input
cq.enQueue(3)
Expected
True
Boolean check
Input
cq.enQueue(4)
Expected
False
Boolean check
Input
cq.Rear()
Expected
3
Test case 5
Input
cq.isFull()
Expected
True
Boolean check
main.py
Hi! I'm Rex 👋
Output
Ready. Press ▶ Run or Ctrl+Enter.