597.Implement a Circular Queue
Easy
Implement a queue that can hold at most
capacity items and run the given operations. "enqueue" adds args[i] and reports 1, or reports 0 if the queue is full; "dequeue" removes and reports the front item (−1 if empty); "front" reports the front item (−1 if empty); "isEmpty" and "isFull" report 1 or 0. Return all reported values in order.
A circular queueCircular Queue (Ring Buffer)A fixed-size queue stored in an array whose indexes wrap around from the end back to 0, so freed slots are reused. solves the wasted-space problem of a simple array queue: when the back reaches the end of the array, it wraps around to the slots freed at the front. The moduloModulo WraparoundUsing % capacity so an index that passes the end of the array continues from 0. operator does the wrapping, giving O(1) operations with no shifting and no wasted space.
Example 1:
Input: capacity = 2, ops = ["enqueue","enqueue","enqueue","dequeue","enqueue","front"], args = [1,2,3,0,4,0]
Output: [1,1,0,1,1,2]
Example 2:
Input: capacity = 1, ops = ["isEmpty","enqueue","isFull"], args = [0,9,0]
Output: [1,1,1]
+ 3 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ capacity ≤ 1000 - ●
1 ≤ ops.length ≤ 1000 - ●
ops[i] is one of "enqueue", "dequeue", "front", "isEmpty", "isFull" - ●
args[i] is the value for "enqueue" and 0 otherwise
capacity =
2
ops =
["enqueue", "enqueue", "enqueue", "dequeue", "enqueue", "front"]
args =
[1, 2, 3, 0, 4, 0]