Replay a Command Script and Record Box State After Each Step
Data Structure DesignAuto-graded · 21 test casesLast updated
Simulate an ordered list of color, delay and move commands on a box, tracking cumulative position and total waited time, and return a state snapshot after every command.
Replay a Command Script
A box on a screen is controlled by a chain of commands that run strictly one after another. Because the real behavior involves timers, you will model it deterministically: instead of actually pausing, a delay command just adds to a running clock.
You are given two lists of equal length:
commands: the name of each command, in the order it runs.params: for each command, a list holding that command's parameters.
Commands
| Name | Parameters | Effect |
|---|---|---|
"setColor" | [color] | The box's color becomes color (a string). |
"wait" | [ms] | The total elapsed time increases by ms. |
"shift" | [dx, dy] | The box moves by dx horizontally and dy vertically, relative to where it currently is. |
Initial state
coloris the empty string"".x = 0andy = 0.elapsed = 0.
Task
Process the commands in order. After each command is applied, record a snapshot of the current state as a dictionary with exactly these keys:
"color": the current color string"x": the accumulated horizontal offset"y": the accumulated vertical offset"elapsed": the total milliseconds waited so far
Return the list of snapshots, one per command, in the same order as the commands.
Rules and edge cases
- Shifts accumulate. Two shifts of
(10, 20)and(-3, 5)leave the box at(7, 25). Negative values are allowed. - A
waitof0leaveselapsedunchanged, but a snapshot is still recorded. - If
setColoris never used,colorremains""in every snapshot. - If the same color is set again, or a later color is set, the most recent one applies from that point onward.
- An empty command list produces an empty result list.
- If a command name is not one of the three above, raise a
ValueError.
Constraints
commandsandparamshave the same length.- Each
params[i]contains exactly the parameters its command needs. - Delays and shift amounts are integers (shifts and the offsets may be negative; delays are non-negative).
- Each snapshot must be an independent dictionary, not a reference to a shared one.
Examples
Example 1
Input: replay_box_commands(['setColor', 'wait', 'shift', 'setColor'], [['blue'], [500], [100, 0], ['green']])
Output: [{'color': 'blue', 'x': 0, 'y': 0, 'elapsed': 0}, {'color': 'blue', 'x': 0, 'y': 0, 'elapsed': 500}, {'color': 'blue', 'x': 100, 'y': 0, 'elapsed': 500}, {'color': 'green', 'x': 100, 'y': 0, 'elapsed': 500}]
Example 2
Input: replay_box_commands(['shift', 'shift', 'wait', 'setColor'], [[10, 20], [-3, 5], [0], ['red']])
Output: [{'color': '', 'x': 10, 'y': 20, 'elapsed': 0}, {'color': '', 'x': 7, 'y': 25, 'elapsed': 0}, {'color': '', 'x': 7, 'y': 25, 'elapsed': 0}, {'color': 'red', 'x': 7, 'y': 25, 'elapsed': 0}]
Example 3
Input: replay_box_commands(['setColor', 'wait', 'setColor'], [['red'], [0], ['red']])
Output: [{'color': 'red', 'x': 0, 'y': 0, 'elapsed': 0}, {'color': 'red', 'x': 0, 'y': 0, 'elapsed': 0}, {'color': 'red', 'x': 0, 'y': 0, 'elapsed': 0}]
Hints
Hint 1
Keep four pieces of state (color, x, y, elapsed) in plain variables and update them as you walk through the commands in order.
Hint 2
A shift must add to the current position instead of replacing it, and a wait only adds to the clock; neither resets anything else.
Hint 3
Build a fresh dictionary after every command and append it to the result, so earlier snapshots are not changed by later commands. Raise ValueError for any unrecognized command name.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This models a chainable object whose commands execute strictly in order. In a real implementation, each call would be put on a queue and a single runner would execute them one at a time, awaiting any timer-based step. Here the timing is replaced by a counter, so the whole thing becomes a simple state machine.
- Start with
color = "",x = 0,y = 0,elapsed = 0. - Walk through the commands in order alongside their parameters.
- Update the state according to the command:
setColorreplaces the color.waitadds the delay toelapsed.shiftaddsdxtoxanddytoy.- Anything else raises
ValueError.
- After each command, append a new dictionary with the current state to the result.
Why it is correct
Commands are processed in exactly the order given, matching the sequential execution guarantee of the queue. Shifts are cumulative because we add to the stored offsets instead of overwriting them, and the clock only moves forward on wait. Every snapshot is a freshly built dictionary, so later updates cannot alter earlier entries.
Complexity
- Time: O(n) for n commands, with O(1) work per command.
- Space: O(n) for the list of snapshots, plus O(1) working state.
Reference solution
from typing import List, Dict
def replay_box_commands(commands: List[str], params: List[List]) -> List[Dict]:
color = ""
x = 0
y = 0
elapsed = 0
snapshots = []
for name, args in zip(commands, params):
if name == "setColor":
color = args[0]
elif name == "wait":
elapsed += args[0]
elif name == "shift":
x += args[0]
y += args[1]
else:
raise ValueError("unknown operation")
snapshots.append({
"color": color,
"x": x,
"y": y,
"elapsed": elapsed,
})
return snapshots