Canvas Replay with Undo and Redo History
Data Structure DesignAuto-graded · 19 test casesLast updated
Simulate a pixel canvas with draw, erase, flood fill, undo and redo, returning a canvas snapshot after every command while keeping the history stacks consistent.
You are building the engine of a tiny drawing program. The canvas is a grid with height rows and width columns. Every cell is either empty (None) or holds a color, which is a string or an integer. A new canvas starts with every cell empty.
A cell is addressed as (x, y), where x is the column and y is the row, both zero-based. In Python the cell is canvas[y][x]. All coordinates are within the canvas.
You are given a list of commands and a parallel list of their arguments. Replay the commands in order and return the state of the canvas after each command.
Commands
| Command | Arguments | Effect |
|---|---|---|
draw | [x, y, color] | Set cell (x, y) to color. |
erase | [x, y] | Set cell (x, y) to empty (None). |
fill | [x, y, color] | Flood fill, described below. |
undo | [] | Go back to the canvas as it was before the most recent change that is currently applied. |
redo | [] | Re-apply the change most recently undone. |
Flood fill
Let original be the value currently in cell (x, y) (it may be None).
- If
originalequalscolor, nothing changes on the canvas. - Otherwise, every cell that holds
originaland can be reached from(x, y)by moving up, down, left or right through cells that all holdoriginalis set tocolor. Diagonal moves do not count, and the fill never leaves the canvas.
History rules
draw,eraseandfillare modifying commands. Each one adds an entry to the undo history and empties the redo history. This happens always, even if the command leaves the canvas unchanged (for example drawing a color already present, erasing an empty cell, or a fill whoseoriginalequalscolor). A laterundowill then step back to an identical canvas.undowith a non-empty undo history moves the current canvas into the redo history and restores the canvas from the most recent undo entry. If the undo history is empty, the canvas is unchanged.redowith a non-empty redo history moves the current canvas into the undo history and restores the most recently saved redo entry. If the redo history is empty, the canvas is unchanged.undoandredothemselves are not modifying commands, so they do not clear the redo history.
Output
Return a list with one entry per command, in order. Each entry is a snapshot of the canvas (a height x width list of lists, indexed [y][x]) taken right after that command, including undo and redo commands and ones that did nothing. Snapshots must be independent copies, so later commands do not alter earlier snapshots.
Function
canvas_history(width, height, commands, args) returns the list of snapshots.
Constraints
1 <= width, height; the canvas may be large (up to a few thousand cells per side).- Up to tens of thousands of commands.
len(commands) == len(args).- Command names are one of
draw,erase,fill,undo,redo. - All coordinates are in bounds.
- Colors are strings or integers and are compared with
==.
Examples
Example 1
Input: canvas_history(3, 2, ['draw', 'draw', 'fill', 'undo', 'redo'], [[0, 0, 'red'], [1, 0, 'red'], [0, 0, 'blue'], [], []])
Output: [[['red', None, None], [None, None, None]], [['red', 'red', None], [None, None, None]], [['blue', 'blue', None], [None, None, None]], [['red', 'red', None], [None, None, None]], [['blue', 'blue', None], [None, None, None]]]
Example 2
Input: canvas_history(2, 2, ['draw', 'erase', 'undo', 'redo'], [[1, 1, 7], [1, 1], [], []])
Output: [[[None, None], [None, 7]], [[None, None], [None, None]], [[None, None], [None, 7]], [[None, None], [None, None]]]
Hints
Hint 1
Keep two stacks of whole canvases: one for undo, one for redo. Think about which stack each command pushes onto and which it pops from.
Hint 2
Flood fill can be done with an explicit stack instead of recursion. Skip any popped cell that no longer holds the original color, and do nothing at all if the original color already equals the new color.
Hint 3
Every draw, erase and fill must push to the undo history and clear the redo history, even if it changes nothing. Also copy rows when you save or output a canvas so later edits do not corrupt stored states.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat each modifying command as a transition between whole-canvas states and keep two stacks of saved canvases:
- Undo stack: the canvas as it was just before each change that is currently applied.
- Redo stack: canvases that were current right before an
undo.
For each command:
draw,erase,fill: copy the canvas asbefore, apply the change, pushbeforeonto the undo stack, and clear the redo stack. This happens even if nothing changed.undo(only if the undo stack is non-empty): push a copy of the current canvas onto the redo stack, then pop the undo stack and make that the current canvas.redo(only if the redo stack is non-empty): push a copy of the current canvas onto the undo stack, then pop the redo stack and make that the current canvas.- After every command, append a row-wise copy of the current canvas to the output.
Flood fill uses an explicit stack. Read original = canvas[y][x]. If it equals color, stop. Otherwise pop cells, skip those that no longer hold original, recolor the rest, and push their in-bounds four neighbors.
Why it is correct
- Undo invariant: the top of the undo stack is the canvas right before the current state was produced. Modifying commands and
redoboth push the pre-state, so the invariant holds on both paths. - Redo invariant:
undopushes the current canvas before swapping, soredorestores exactly the state that was left. - Branching: a new modifying command starts a new timeline, so clearing the redo stack matches the rule that redo history is discarded.
- Fill: a cell is recolored only if it holds
originaland is four-connected to the start throughoriginalcells. Recolored cells no longer equaloriginal, so each is painted once, and duplicate stack entries are skipped. Theoriginal != colorguard prevents an endless loop. - Aliasing: copying rows is enough because cell values are immutable, so saved states and snapshots never change afterward.
Complexity
Let N be the number of commands and C = width * height.
- Time: each command copies the canvas a constant number of times and fill touches each cell a constant number of times, so O(C) per command and O(N * C) overall.
- Space: the stacks and the returned snapshots each hold up to O(N) canvases, so O(N * C). The output size makes this unavoidable.
In a real editor you would store only the changed cells (old and new values) per command and apply them on undo or redo. Here the output already costs O(C) per command, so full snapshots are the simplest correct choice.
Reference solution
from typing import List
def canvas_history(width: int, height: int, commands: List[str], args: List[List]) -> List[List[List]]:
canvas = [[None for _ in range(width)] for _ in range(height)]
undo_stack = []
redo_stack = []
snapshots = []
for command, params in zip(commands, args):
if command in ("draw", "erase", "fill"):
before = [row[:] for row in canvas]
if command == "draw":
x, y, color = params
canvas[y][x] = color
elif command == "erase":
x, y = params
canvas[y][x] = None
else:
x, y, color = params
original = canvas[y][x]
if original != color:
stack = [(x, y)]
while stack:
cx, cy = stack.pop()
if canvas[cy][cx] != original:
continue
canvas[cy][cx] = color
if cx > 0:
stack.append((cx - 1, cy))
if cx + 1 < width:
stack.append((cx + 1, cy))
if cy > 0:
stack.append((cx, cy - 1))
if cy + 1 < height:
stack.append((cx, cy + 1))
undo_stack.append(before)
redo_stack.clear()
elif command == "undo":
if undo_stack:
redo_stack.append([row[:] for row in canvas])
canvas = undo_stack.pop()
elif command == "redo":
if redo_stack:
undo_stack.append([row[:] for row in canvas])
canvas = redo_stack.pop()
snapshots.append([row[:] for row in canvas])
return snapshots