Early Access: 87 spots left.

Claim
Coding Interview PatternsQueuesDesign Circular Queue

Problems

Design Circular Queue

Medium·Tagsqueuearraydesign

Problem Statement

Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle and the last position is connected back to the first position to make a circle. It is also called a "Ring Buffer". One of the benefits of the circular queue is that we can make use of the spaces in front of the queue. In a normal queue, once the queue becomes full, we cannot insert the next element even if there is a space in front of the queue. But using the circular queue, we can use the space to store new values. To allow our automated runner to test your class, write a function `runCircularQueue` that takes an array of string operations (`"MyCircularQueue"`, `"enQueue"`, `"deQueue"`, `"Front"`, `"Rear"`, `"isEmpty"`, `"isFull"`) and an array of integer arguments for those operations. It should return an array of integers representing the results: - Return `1` for `true` or success (e.g., successful enqueue). - Return `0` for `false` or failure (e.g., enqueueing when full). - Return `-1` for `null` initializations or when retrieving from an empty queue.

Examples

Example 1
Input
ops: ["MyCircularQueue", "enQueue", "enQueue", "enQueue", "enQueue", "Rear", "isFull", "deQueue", "enQueue", "Rear"], args: [[3], [1], [2], [3], [4], [], [], [], [4], []]
Output
"[-1, 1, 1, 1, 0, 3, 1, 1, 1, 4]"
Why
Initialize with size 3. Enqueue 1, 2, 3 (returns 1). Enqueue 4 fails because it is full (returns 0). Rear is 3. isFull is true (1). Dequeue removes 1 (returns 1). Enqueue 4 succeeds (returns 1). Rear is now 4.

Constraints

  • 1 <= ops.length <= 1000
  • 1 <= k <= 1000
  • 0 <= value <= 1000

Hints

Stuck? Reveal a nudge toward the right pattern, one step at a time.

Hint 1
You don't need to actually shift elements in the array. That would take O(N) time. Instead, use a fixed-size array and track the `head` index.
Hint 2
Keep a `count` variable to track how many items are currently in the queue. This makes checking `isEmpty` and `isFull` extremely easy (count == 0 and count == k).
Hint 3
To find the index where the next element should be enqueued (the tail), you can use the formula: `(head + count) % k`, where `% k` forces the index to wrap around to the beginning if it goes out of bounds!