Skip to contentKEEP THE CRAFTTHE SANCTUARY

Design Circular Queue

Build a fixed-size first-in, first-out queue on a plain list whose free slots are reused by wrapping around.

The problem

Design a class MyCircularQueue. MyCircularQueue(k) creates an empty queue that can hold at most k values. enQueue(value) adds a value at the back and returns True, or returns False if the queue is full. deQueue() removes the value at the front and returns True, or returns False if the queue is empty. Front() and Rear() return the value at the front and at the back, or -1 if the queue is empty. isEmpty() and isFull() return True or False. Store the values in a fixed-size Python list that reuses freed slots; do not use a built-in queue type such as collections.deque or queue.Queue. k is at most 1,000, values are between 0 and 1,000, and there are at most 3,000 calls.

Starter code

class MyCircularQueue:
    def __init__(self, k):
        pass

Public examples

  1. obj = MyCircularQueue(3) obj.enQueue(1) obj.enQueue(2) obj.enQueue(3) obj.enQueue(4) obj.Rear() obj.isFull() obj.deQueue() obj.enQueue(4) obj.Rear()gives[None, True, True, True, False, 3, True, True, True, 4]
  2. obj = MyCircularQueue(1) obj.enQueue(7) obj.deQueue() obj.enQueue(9) obj.Front() obj.Rear()gives[None, True, True, True, 9, 9]
  3. obj = MyCircularQueue(3) obj.enQueue(2) obj.enQueue(8) obj.deQueue() obj.Front()gives[None, True, True, True, 8]

Solving it in the practice book needs an active paid plan.

Open it in the practice book
One thought at a time.