MediumArrayLinked ListDesignQueue

Design Circular Queue

LeetCode
1 approach, code in all languages

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 <= 1000
  • 0 <= value <= 1000
  • At most 3000 calls will be made to enQueue, deQueue, Front, Rear, isEmpty, and isFull.
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now