Bounded Circular Queue
Problem statement
Implement a FIFO queue whose storage is one fixed-size array of length capacity. The queue starts empty. Process operations in order and return one integer result for each operation.
[0, x]: enqueuex. Return1if it is inserted. If the queue is full, return0and leave the queue unchanged.[1, 0]: dequeue the oldest value and return it. Return-1when empty.[2, 0]: return the front value without removing it. Return-1when empty.[3, 0]: return the current number of stored values.
Stored values are nonnegative, so -1 is reserved for an empty dequeue or front operation. Do not overwrite a value when full or resize the queue storage. Reuse freed array positions. Aim for constant time per operation after allocating storage. The returned results may use a separate array.
Function
runCircularQueue(capacity: int, operations: int[][]) → int[]Examples
Example 1
capacity = 2operations = [[0,7],[0,9],[0,11],[2,0],[1,0],[0,11],[1,0],[1,0],[1,0]]return = [1,1,0,7,7,1,9,11,-1]The first two enqueues succeed, so the queue is [7,9]. Enqueuing 11 fails because the queue is full. Front returns 7 without removing it. After removing 7, enqueuing 11 succeeds. The remaining dequeues return 9, 11, and then -1 for an empty queue.
Example 2
capacity = 1operations = [[2,0],[3,0],[0,0],[3,0],[0,5],[1,0],[2,0]]return = [-1,0,1,1,0,0,-1]An empty queue has front -1 and size 0. Enqueuing the value 0 succeeds and makes the size 1. The next enqueue fails. Dequeue returns the stored value 0; the queue is then empty again.
Example 3
capacity = 3operations = []return = []No operations are requested, so the returned array is empty.
Constraints
1 <= capacity <= 10000 <= operations.length <= 5000- Every operation has exactly two integers.
- Every operation entry is between
0and1000000, inclusive. - Each row is
[code, argument], wherecodeis0,1,2, or3. For codes1,2, and3, the argument is0.