Sorted Buffer Simulator with Insert and Snapshot Commands
Data Structure DesignAuto-graded · 18 test casesLast updated
Simulate a container that keeps integers in ascending order under insert and snapshot commands, testing binary-search insertion, duplicate handling, and copying versus aliasing.
Sorted Buffer Simulator
You are modelling a small container that always holds its integers in non-decreasing order. The container starts empty and is driven by a sequence of commands.
You are given two lists of equal length:
commands: a list of strings, each naming a command.payloads: a list of integer lists.payloads[i]holds the arguments forcommands[i].
Process the commands from left to right. Each command produces exactly one entry in the output list.
Supported commands
"insert":payloads[i]has the form[v]. Addvto the container so the contents stay in non-decreasing order. If equal values are already present, the new value is placed after all of them. This command addsNoneto the output."data":payloads[i]is an empty list. Add to the output a separate copy of the current contents, from smallest to largest. Later inserts must not change a snapshot that has already been recorded.
Any other command name is invalid and must raise a ValueError.
Return value
Return a list with one entry per command: None for each insert, and a list of integers for each data.
Constraints
len(commands) == len(payloads)- Values are integers and may be negative or repeated.
- Calling
dataon an empty container returns an empty list. - Snapshots must be independent copies, not views of the live container.
- An unrecognized command raises
ValueError. - Aim for a binary search to find the insertion point rather than a linear scan.
Examples
Example 1
Input: sorted_buffer_commands(['insert', 'insert', 'insert', 'data'], [[5], [2], [8], []])
Output: [None, None, None, [2, 5, 8]]
Example 2
Input: sorted_buffer_commands(['data', 'insert', 'data', 'insert', 'data'], [[], [4], [], [4], []])
Output: [[], None, [4], None, [4, 4]]
Hints
Hint 1
The container is always sorted, so the insertion position can be found with binary search instead of scanning.
Hint 2
For equal values, the new element must go after the existing equal ones. Choose the binary-search variant that returns the rightmost valid position.
Hint 3
When handling `data`, append a copy of the list rather than the list itself, otherwise later inserts will change earlier results.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Keep a single Python list that is always sorted in non-decreasing order, and walk through the commands once.
- insert: use
bisect_rightto find the indexisuch that everything beforeiis less than or equal to the new value and everything fromionward is strictly greater. Insert the value ati. RecordNone. - data: record
values.copy(), so the snapshot is independent of future changes. - anything else: raise
ValueError.
Why it is correct
Invariant: before each command, the list is sorted. bisect_right returns a position where all earlier elements are <= v and all later ones are > v. Inserting v there keeps the list sorted, and it also places v after any equal elements, as required. data does not modify the list, and because it returns a copy, later inserts cannot alter earlier output. By induction, every snapshot is sorted and contains exactly the values inserted so far.
For plain integers, equal values are indistinguishable, so the "insert after equals" rule does not change the visible output, but using bisect_right follows the specification exactly.
Complexity
insert: O(log n) for the search plus O(n) to shift the tail of the list.data: O(n) to copy.- Over
kcommands, the worst case is O(k^2) time. Extra space is O(n) for the container, plus the total size of all snapshots in the output.
Reference solution
from bisect import bisect_right
from typing import List, Optional
def sorted_buffer_commands(commands: List[str], payloads: List[List[int]]) -> List[Optional[List[int]]]:
values: List[int] = []
results: List[Optional[List[int]]] = []
for command, args in zip(commands, payloads):
if command == "insert":
value = args[0]
index = bisect_right(values, value)
values.insert(index, value)
results.append(None)
elif command == "data":
results.append(values.copy())
else:
raise ValueError("Unsupported operation")
return results