Replay Operations on a Fixed-Capacity FIFO Buffer
Data Structure DesignAuto-graded · 18 test casesLast updated
Simulate a bounded first-in-first-out buffer over a list of put and take commands, rejecting any command that would have to wait.
Replay Operations on a Fixed-Capacity FIFO Buffer
A bounded buffer holds at most capacity items and hands them back in the order they were stored (first in, first out). In a concurrent program, a put on a full buffer or a take on an empty buffer would make the calling thread wait. Here you replay a recorded, single-threaded log of commands, so waiting is never possible. Any command that would have to wait is an error.
Write a function that processes the commands in order and returns what each one produced.
Commands
You are given three inputs:
capacity: the maximum number of items the buffer can hold at once.operations: a list of command names, each either"put"or"take".arguments: a list of the same length asoperations. The entry at indexiis the argument list foroperations[i].
The commands behave as follows:
"put": its argument list has exactly one element, the item to store. The item goes at the back of the buffer. The result for this command isNone."take": its argument list is empty. The item at the front of the buffer is removed and becomes the result for this command.
Items can be any values, such as integers or strings. Treat them as opaque and return exactly what was stored.
Output
Return a list with one entry per command, in the same order as operations. A put contributes None and a take contributes the item it removed.
Error rules
Raise a ValueError in each of these situations:
capacityis not a positive integer (checked before any command is processed, even if there are no commands).- A
putis issued while the buffer already holdscapacityitems. - A
takeis issued while the buffer is empty. - A command name is neither
"put"nor"take".
When an error is raised, no result list is returned.
Constraints
capacityis an integer. A valid value is at least 1.len(operations) == len(arguments).- Each
puthas exactly one argument. Eachtakehas none. - Items are returned in the exact order they were stored.
- Each command should run in constant time, so the whole replay takes time linear in the number of commands.
Examples
Example 1
Input: replay_bounded_buffer(2, ['put', 'put', 'take', 'put', 'take', 'take'], [[1], [2], [], [3], [], []])
Output: [None, None, 1, None, 2, 3]
Example 2
Input: replay_bounded_buffer(1, ['put', 'take', 'put', 'take'], [['a'], [], ['b'], []])
Output: [None, 'a', None, 'b']
Example 3
Input: replay_bounded_buffer(3, ['put', 'put', 'put', 'take', 'take', 'put', 'take', 'take'], [[5], [5], [-1], [], [], [8], [], []])
Output: [None, None, None, 5, 5, None, -1, 8]
Hints
Hint 1
You do not need threads or locks. The log is sequential, so a plain data structure plus a size check is enough.
Hint 2
Removing from the front of a Python list is slow. Use a structure with constant-time removal from the front, such as collections.deque, or keep a head index.
Hint 3
Before each put, compare the current size to capacity. Before each take, check that the buffer is not empty. Raise ValueError in the failing cases instead of waiting.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
In a real concurrent bounded buffer, a put on a full buffer and a take on an empty buffer would sleep until another thread made room or supplied an item. In this replay there is only one caller, so nobody could ever wake a sleeper. The problem therefore reduces to a sequential simulation in which "would wait" becomes ValueError.
- Validate
capacityup front and raiseValueErrorif it is not positive. - Keep the stored items in a
deque, which gives constant-time append at the back and constant-time removal from the front. - Walk through the commands in order:
- For
put, if the buffer already holdscapacityitems, raiseValueError. Otherwise append the item and recordNone. - For
take, if the buffer is empty, raiseValueError. Otherwise pop from the front and record that item. - For any other command name, raise
ValueError.
- For
- Return the recorded results.
Why it is correct
The deque preserves insertion order, and items are only removed from the front, so each take returns the oldest item still stored, which is the FIFO rule. The size check before each put ensures the buffer never exceeds capacity. The emptiness check before each take ensures nothing is removed from an empty buffer. Together these checks give exactly the error behavior described, and every successful command produces the specified result.
Complexity
- Time: O(n) for n commands, since each command takes constant time.
- Space: O(min(capacity, n)) for the buffer, plus O(n) for the result list.
Reference solution
from collections import deque
from typing import List
def replay_bounded_buffer(capacity: int, operations: List[str], arguments: List[List]) -> List:
if capacity <= 0:
raise ValueError("capacity must be positive")
buffer = deque()
results = []
for operation, args in zip(operations, arguments):
if operation == "put":
if len(buffer) >= capacity:
raise ValueError("put would block")
buffer.append(args[0])
results.append(None)
elif operation == "take":
if not buffer:
raise ValueError("take would block")
results.append(buffer.popleft())
else:
raise ValueError("unknown operation")
return results