Fixed-Size Ring Buffer Command Simulator
Data Structure DesignAuto-graded · 18 test casesLast updated
Simulate a bounded FIFO ring buffer driven by a list of commands, handling wrap-around, full and empty states, and returning each command's result in order.
Ring Buffer Command Simulator
A ring buffer is a first-in-first-out container with a fixed capacity. Its storage is a single array of that size, and when an index moves past the last slot it wraps back to the first. Your job is to simulate such a buffer by running a sequence of commands against it and reporting what each command returns.
You are given two parallel lists:
operations: command names, processed from left to right.arguments: for each command, the list of arguments it takes.
The i-th entry of arguments belongs to the i-th entry of operations.
Commands
| Command | Arguments | Behavior | Output |
|---|---|---|---|
"init" | [k] | Creates an empty buffer with capacity k. | None |
"enqueue" | [value] | Adds value at the back if there is free space. A full buffer is left unchanged and nothing is overwritten. | True if added, otherwise False |
"dequeue" | [] | Removes the oldest element (the front) if there is one. | True if removed, otherwise False |
"front" | [] | Reads the oldest element without removing it. | The value, or -1 if the buffer is empty |
"rear" | [] | Reads the most recently added element still in the buffer, without removing it. | The value, or -1 if the buffer is empty |
"is_empty" | [] | Checks whether the buffer holds no elements. | True or False |
"is_full" | [] | Checks whether the buffer holds exactly k elements. | True or False |
The first command is always "init", and it appears exactly once.
Task
Return a list with one entry per command, in the same order as operations, holding the output of each command as described in the table.
Elements leave the buffer in the same order they entered. Freed slots are reused, so after removing elements the buffer can accept new ones up to its capacity again.
Constraints
1 <= k <= 10000 <= value <= 1000len(operations) == len(arguments)- Every command name is one of the seven listed above.
- Arguments are always provided in the form shown in the table.
Examples
Example 1
Input: simulate_ring_buffer(['init', 'enqueue', 'enqueue', 'enqueue', 'enqueue', 'rear', 'is_full', 'dequeue', 'enqueue', 'rear'], [[3], [1], [2], [3], [4], [], [], [], [4], []])
Output: [None, True, True, True, False, 3, True, True, True, 4]
Example 2
Input: simulate_ring_buffer(['init', 'front', 'rear', 'is_empty', 'is_full', 'dequeue'], [[1], [], [], [], [], []])
Output: [None, -1, -1, True, False, False]
Example 3
Input: simulate_ring_buffer(['init', 'enqueue', 'dequeue', 'dequeue', 'front', 'rear', 'is_empty', 'is_full'], [[2], [7], [], [], [], [], [], []])
Output: [None, True, True, False, -1, -1, True, False]
Hints
Hint 1
Keep a fixed-size array plus two integers: the index of the front element and the number of stored elements. Everything else can be derived from these.
Hint 2
The slot for the next write is (head + count) % k, and the rear element sits at (head + count - 1) % k. Using an explicit count avoids confusing an empty buffer with a full one.
Hint 3
Dequeue only needs to advance head by one (mod k) and decrease count; the old slot can stay as it is, since it will be overwritten later. Check for full or empty before changing any state.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Store the elements in a preallocated array of length k and track two integers:
head: the index of the oldest element.size: how many elements are currently stored.
All other positions follow from these two:
- The next write goes to
(head + size) % k. - The newest element is at
(head + size - 1) % k.
The modulo makes indices that run past the end wrap around to the start.
Using an explicit size avoids the classic ambiguity of head/tail pointers, where an empty and a full buffer look identical (head == tail).
Command handling:
init: allocate the array, sethead = 0,size = 0, outputNone.enqueue: ifsize == k, outputFalsewithout touching anything. Otherwise write the value at(head + size) % k, incrementsize, outputTrue.dequeue: ifsize == 0, outputFalse. Otherwise advanceheadby one modulok, decrementsize, outputTrue.front/rear: output-1if empty, otherwise read the array atheador at(head + size - 1) % k.is_empty/is_full: comparesizewith0andk.
Why it is correct
The invariant is that the queue contents from front to back are exactly buf[head], buf[(head+1) % k], ..., buf[(head+size-1) % k], with 0 <= size <= k.
- Initially the buffer is empty, so the invariant holds.
- Enqueue writes just after the current last element, into a slot that is free because
size < k, and then extends the window by one. - Dequeue shrinks the window from the front. The stale value left in the old slot lies outside the window and is overwritten before it could be read.
frontandrearread the two ends of the window, and return-1when the window is empty. Values are non-negative, so-1is never a real element.
Since elements are only added at the back and removed from the front, FIFO order is preserved, and a full buffer is never overwritten.
Complexity
- Time: O(1) per command, so O(m) for m commands.
- Space: O(k) for the buffer, plus O(m) for the output list.
Reference solution
from typing import List
def simulate_ring_buffer(operations: List[str], arguments: List[List[int]]) -> List[object]:
buf = []
head = 0
size = 0
out = []
for op, args in zip(operations, arguments):
if op == "init":
buf = [0] * args[0]
head = 0
size = 0
out.append(None)
elif op == "enqueue":
if size == len(buf):
out.append(False)
else:
buf[(head + size) % len(buf)] = args[0]
size += 1
out.append(True)
elif op == "dequeue":
if size == 0:
out.append(False)
else:
head = (head + 1) % len(buf)
size -= 1
out.append(True)
elif op == "front":
out.append(-1 if size == 0 else buf[head])
elif op == "rear":
out.append(-1 if size == 0 else buf[(head + size - 1) % len(buf)])
elif op == "is_empty":
out.append(size == 0)
elif op == "is_full":
out.append(size == len(buf))
return out