Problem · Queue
Ring Buffer Operations
Learn this problemProblem statement
Implement a fixed-capacity ring buffer and process a batch of operations in order. The buffer starts empty.
For each index i, execute operations[i] and append one integer to the result:
push: if the buffer is not full, insertvalues[i]at the back and append1. If the buffer is full, leave it unchanged and append0.pop: if the buffer is not empty, remove and append the oldest value. If it is empty, append-1.front: if the buffer is not empty, append the oldest value without removing it. If it is empty, append-1.size: append the current number of values in the buffer.
When either end reaches the physical end of the backing array, it must wrap around to the beginning.
Function
processRingBuffer(capacity: int, operations: String[], values: int[]) → int[]Examples
Example 1
capacity = 3operations = ["push","push","front","pop","size"]values = [10,20,0,0,0]return = [1,1,10,10,1]The two pushes succeed. The front value is 10; popping removes and returns it, leaving one value in the buffer.
Example 2
capacity = 2operations = ["push","push","push","pop","push","front","size"]values = [5,6,7,0,8,0,0]return = [1,1,0,5,1,6,2]The third push fails because the capacity is 2. After popping 5, pushing 8 reuses the freed circular slot. The front remains 6.
Example 3
capacity = 1operations = ["pop","front","size","push","push","pop","pop","size"]values = [0,0,0,42,99,0,0,0]return = [-1,-1,0,1,0,42,-1,0]Empty reads return -1. The first push succeeds, the next push fails while full, and popping 42 makes the capacity-one buffer empty again.
Constraints
1 <= capacity <= 10^51 <= operations.length = values.length <= 10^5- Every operation is
push,pop,front, orsize. 0 <= values[i] <= 10^9values[i]is used only whenoperations[i]ispush.