KatInterview

Sorted Buffer Simulator with Insert and Snapshot Commands

Data Structure DesignAuto-graded · 18 test cases
EasyAuto-gradedData Structure Designbinary-searchsimulationsorted-list

Last 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 for commands[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]. Add v to 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 adds None to 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 data on 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.