Design Circular Queue
1 approach, code in every language
Problem description
Design a circular queue, a fixed-size FIFO buffer that reuses the space freed by dequeued elements by wrapping the tail back to the beginning of the storage. This ring layout lets you keep enqueuing into slots that earlier elements have vacated instead of wasting them.
Implement the class MyCircularQueue. The constructor sets the queue capacity to k. enQueue(value) inserts an element at the back and returns whether it succeeded. deQueue() removes an element from the front and returns whether it succeeded. 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() and isFull() report whether the queue is empty or at capacity.
Example 1
Input: operations = ["MyCircularQueue", "enQueue", "enQueue", "enQueue", "enQueue", "Rear", "isFull", "deQueue", "enQueue", "Rear"] args = [[3], [1], [2], [3], [4], [], [], [], [4], []]
Output: [null, true, true, true, false, 3, true, true, true, 4]
With capacity 3, the first three enQueue calls succeed and the fourth fails because the queue is full. Rear is 3 and isFull is true. After one deQueue, enQueue(4) fits and Rear becomes 4.
Example 2
Input: operations = ["MyCircularQueue", "isEmpty", "enQueue", "Front", "deQueue", "isEmpty"] args = [[2], [], [8], [], [], []]
Output: [null, true, true, 8, true, true]
A fresh queue is empty. After enQueue(8), Front is 8. Dequeuing that only element leaves the queue empty again.
Constraints
1 <= k <= 10000 <= value <= 1000At most 3000 calls will be made to enQueue, deQueue, Front, Rear, isEmpty, and isFull.
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.
1,194 problems · 15,062 graded tests · free