Replay Operations on a Fixed-Size Ring Buffer Queue
Data Structure DesignAuto-graded · 18 test casesLast updated
Simulate a fixed-capacity circular FIFO queue from an operation log, handling wraparound, full and empty states, and logical index lookups in constant time per operation.
Ring Buffer Queue Replay
A ring buffer is a fixed-size array used as a FIFO queue. New items are written after the last live item, wrapping to the start of the array when the end is reached. Because the array is allocated once and never resized, it avoids per-element allocation and keeps its data contiguous in memory, which makes it a popular choice for high-throughput message passing.
You are given a log of operations to apply, in order, to one such queue. Return the result of every operation.
Operations
Each operation is a string in operations, and the entry at the same position in arguments is its argument list.
| Operation | Arguments | Behavior | Result |
|---|---|---|---|
"init" | [capacity] | Create an empty queue that can hold at most capacity items. | None |
"enqueue" | [val] | Add val at the back. If the queue already holds capacity items, do nothing. | True if added, False if the queue was full |
"dequeue" | [] | Remove the front (oldest) item. | The removed value, or -1 if the queue is empty |
"get" | [index] | Read, without removing, the item index positions behind the front (0 is the front). | The value, or -1 if index is not smaller than the current number of items |
"is_empty" | [] | Check whether the queue holds no items. | True or False |
"is_full" | [] | Check whether the queue holds exactly capacity items. | True or False |
Details
- The first operation is always
"init". - A rejected
enqueueon a full queue must not change the queue in any way. Existing items are never overwritten. getis judged against the number of items currently stored, not against the capacity. Slots that held items removed earlier are not valid positions.- Values stored in the queue are never negative, so
-1is unambiguous as a "nothing here" marker. - Aim for constant time per operation, using one buffer allocated up front.
Output
Return a list with one entry per operation, in the same order as the input. The entry for "init" is None.
Constraints
1 <= capacity <= 10^50 <= val <= 10^90 <= index < capacityoperationsandargumentshave the same length.- Each operation should run in
O(1)time and the buffer must not be reallocated afterinit.
Examples
Example 1
Input: replay_ring_queue(['init', 'enqueue', 'enqueue', 'enqueue', 'enqueue', 'get', 'dequeue', 'enqueue', 'get'], [[3], [10], [20], [30], [40], [1], [], [40], [2]])
Output: [None, True, True, True, False, 20, 10, True, 40]
Example 2
Input: replay_ring_queue(['init', 'is_empty', 'dequeue', 'enqueue', 'is_full', 'get', 'get', 'dequeue', 'dequeue', 'is_empty'], [[1], [], [], [7], [], [0], [1], [], [], []])
Output: [None, True, -1, True, True, 7, -1, 7, -1, True]
Hints
Hint 1
Keep three pieces of state: the buffer, the physical index of the front item, and the count of stored items.
Hint 2
The next free slot is (front + size) % capacity, and the item at logical offset i lives at (front + i) % capacity. Tracking size explicitly avoids confusing a full queue with an empty one.
Hint 3
For get, validate the index against the current size rather than the capacity, since stale slots may still contain old values.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Allocate a single list of length capacity when init is processed, and track two integers:
front: the physical index of the oldest item.size: how many items are currently stored.
The live items occupy slots front, front+1, ..., front+size-1, taken modulo capacity, in FIFO order. From this:
- Enqueue: if
size == capacity, returnFalseand change nothing. Otherwise write the value to slot(front + size) % capacity, incrementsize, and returnTrue. - Dequeue: if
size == 0, return-1. Otherwise readbuffer[front], advancefrontto(front + 1) % capacity, decrementsize, and return the value. - Get: if
index >= size(or negative), return-1. Otherwise returnbuffer[(front + index) % capacity]. - is_empty / is_full: compare
sizewith0andcapacity.
Each operation's result is appended to the output list in order, with None for init.
Why it is correct
The invariant is that the live items sit in the slots front .. front+size-1 (mod capacity) in insertion order. Enqueue writes only to the first slot after that range, and only when a free slot exists, so live data is never overwritten. Dequeue removes the oldest item and shifts the range start forward by one. Get checks the offset against size, so slots that are stale (holding values removed earlier) are never exposed. Keeping size explicitly removes the ambiguity that front == tail holds for both a full and an empty queue. The modulo handles wraparound.
Complexity
- Time:
O(1)per operation, soO(m)formoperations. - Space:
O(capacity)for the buffer, plus the output list.
Reference solution
from typing import List
def replay_ring_queue(operations: List[str], arguments: List[List[int]]) -> List:
buffer = None
capacity = 0
front = 0
size = 0
results = []
for operation, args in zip(operations, arguments):
if operation == "init":
capacity = args[0]
buffer = [0] * capacity
front = 0
size = 0
results.append(None)
elif operation == "enqueue":
if size == capacity:
results.append(False)
else:
position = (front + size) % capacity
buffer[position] = args[0]
size += 1
results.append(True)
elif operation == "dequeue":
if size == 0:
results.append(-1)
else:
value = buffer[front]
front = (front + 1) % capacity
size -= 1
results.append(value)
elif operation == "get":
index = args[0]
if index < 0 or index >= size:
results.append(-1)
else:
results.append(buffer[(front + index) % capacity])
elif operation == "is_empty":
results.append(size == 0)
elif operation == "is_full":
results.append(size == capacity)
return results