Design Circular Queue

MediumDesigndesign

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Implement a bounded FIFO queue, MyCircularQueue, backed by a fixed-size buffer whose end wraps around to its start (a ring buffer). - MyCircularQueue(k) creates an empty queue that can hold at most k elements. - enQueue(value) adds value at the rear. Returns true on success, or false if the queue is full. - deQueue() removes the front element. Returns true on success, or false if the queue is empty. - Front() returns the front element, or -1 if the queue is empty. - Rear() returns the last element, or -1 if the queue is empty. - isEmpty() / isFull() report whether the queue holds zero / k elements. Do not use a built-in queue type. Every operation must run in O(1).

Examples

Input: ["MyCircularQueue","enQueue","enQueue","enQueue","Rear","isFull","deQueue","enQueue","Front","Rear"] [[2],[5],[6],[7],[],[],[],[7],[],[]]
Output: [null,true,true,false,6,true,true,true,6,7]
Capacity is 2, so the third `enQueue` fails. After removing 5 there is room for 7, leaving 6 at the front and 7 at the rear.
Input: ["MyCircularQueue","Front","deQueue","isEmpty","enQueue","isFull","Rear"] [[1],[],[],[],[9],[],[]]
Output: [null,-1,false,true,true,true,9]
An empty queue reports -1 for `Front` and false for `deQueue`. With capacity 1, a single element makes it full.

Constraints

  • 1 <= k <= 1000
  • 0 <= value <= 1000
  • At most 3000 calls are made in total.

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More design problems