Simulate Stacked Rectangles on a Small Text Canvas
Data Structure DesignAuto-graded · 23 test casesLast updated
Simulate add, remove, reorder and render commands on a layered character canvas, resolving overlaps by layer order and clipping shapes at the edges.
You are given a text canvas with canvas_width columns and canvas_height rows, and a list of commands to run against it in order. The canvas holds filled rectangles stacked in layers. Each rectangle is drawn with one character, and a rectangle on a higher layer hides whatever is beneath it.
Coordinates are (x, y): x is the column (0 at the left) and y is the row (0 at the top). A rectangle with top-left corner (x, y), width w and height h covers the cells with x <= column < x + w and y <= row < y + h.
Commands
Command i is named by commands[i] and takes the argument list command_args[i]:
| Command | Arguments | Effect | Result |
|---|---|---|---|
"add_rectangle" | [shape_id, x, y, w, h, fill] | Places a new rectangle on the top layer. | True if added, otherwise False. |
"remove" | [shape_id] | Deletes the rectangle with that id. | True if it existed, otherwise False. |
"bring_to_front" | [shape_id] | Moves the rectangle to the top layer. | True if it existed, otherwise False. |
"send_to_back" | [shape_id] | Moves the rectangle to the bottom layer. | True if it existed, otherwise False. |
"render" | [] | Draws the current canvas. | A list of canvas_height strings, each of length canvas_width. |
Rules
add_rectanglereturnsFalseand changes nothing ifshape_idis already in use, or ifw <= 0orh <= 0. A removed id may be used again, and the new rectangle goes on the top layer.- Rectangles may extend beyond the canvas, in whole or in part, and they may have negative coordinates. They are accepted and stored as given. Only the cells inside the canvas are drawn, so a rectangle entirely outside the canvas is valid but invisible.
- Commands that fail (unknown id, duplicate id, bad size) leave the state unchanged.
- Reordering a rectangle that is already in the requested position still returns
True. - When rendering, every cell not covered by any rectangle shows
'.'. A covered cell shows the fill character of the highest-layer rectangle covering it. - Moving a rectangle to another layer changes only the layer order. It does not change the rectangle's position or size.
Task
Implement the function so that it runs all commands in order and returns a list of results, one entry per command, in the same order as the commands.
Constraints
1 <= canvas_width, canvas_height <= 100len(commands) == len(command_args), and every command is one of the five names above.shape_idis a string andfillis a single character.x,y,w,hare integers. Coordinates may be negative or larger than the canvas, andwandhmay be zero or negative (in which case adding fails).
Examples
Example 1
Input: run_canvas_commands(10, 6, ['add_rectangle', 'add_rectangle', 'render', 'bring_to_front', 'render'], [['A', 1, 1, 4, 3, 'A'], ['B', 3, 2, 4, 3, 'B'], [], ['A'], []])
Output: [True, True, ['..........', '.AAAA.....', '.AABBBB...', '.AABBBB...', '...BBBB...', '..........'], True, ['..........', '.AAAA.....', '.AAAABB...', '.AAAABB...', '...BBBB...', '..........']]
Example 2
Input: run_canvas_commands(10, 6, ['render', 'add_rectangle', 'render', 'remove', 'render'], [[], ['x', -2, 4, 5, 4, '#'], [], ['missing'], []])
Output: [['..........', '..........', '..........', '..........', '..........', '..........'], True, ['..........', '..........', '..........', '..........', '###.......', '###.......'], False, ['..........', '..........', '..........', '..........', '###.......', '###.......']]
Example 3
Input: run_canvas_commands(5, 4, ['add_rectangle', 'add_rectangle', 'send_to_back', 'render'], [['a', 0, 0, 5, 4, 'a'], ['b', 1, 1, 2, 2, 'b'], ['b'], []])
Output: [True, True, True, ['aaaaa', 'aaaaa', 'aaaaa', 'aaaaa']]
Hints
Hint 1
Keep the shapes in a structure that remembers layer order from bottom to top and still lets you look up a shape by id. Python's OrderedDict has move_to_end for exactly this.
Hint 2
You do not need to maintain a pixel grid while commands run. Store the shapes, and only build the grid when a render command arrives.
Hint 3
To render, start with a grid of '.', then paint shapes from the bottom layer to the top so later shapes overwrite earlier ones. Clip each rectangle's column and row ranges to the canvas so out-of-bounds shapes need no special handling.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Two separate concerns drive the design: layer order and drawing.
Layer order. Store the rectangles in an OrderedDict keyed by shape_id, where iteration order runs from the bottom layer to the top layer. This gives:
- adding a shape: insert at the end, so it is on top;
remove:popby id;bring_to_front:move_to_end(id);send_to_back:move_to_end(id, last=False).
All of these take O(1) time and also double as the existence check that decides whether the command returns True or False.
Drawing. Rasterize lazily, only when a render command arrives:
- Start with a grid filled with
'.'. - Walk the shapes from bottom to top.
- For each shape, clip its column range to
[max(0, x), min(canvas_width, x + w))and its row range to[max(0, y), min(canvas_height, y + h)). If either range is empty, skip the shape. - Overwrite the cells in the clipped range with the shape's fill character.
Why it is correct
- Painting goes bottom to top, so the last write to any cell comes from the highest-layer shape covering it. That is exactly the occlusion rule. Cells that no shape covers keep
'.'. - Clipping with
maxandminhandles negative coordinates, shapes that overflow the canvas, and shapes entirely outside it, all without special cases and without index errors. - Invalid or duplicate adds are rejected before any state is changed, and operations on unknown ids return
Falsewithout touching the order, so failed commands never alter the canvas. - Each live id appears exactly once in the
OrderedDict, and reordering only moves its entry, so the layer order is always a valid ordering of the live shapes. Re-adding a removed id puts it on top.
Complexity
Let n be the number of live shapes and W x H the canvas size.
add_rectangle,remove,bring_to_front,send_to_back: O(1) each.render: O(W·H + the sum of the clipped areas of all shapes), which is at most O(W·H·(n + 1)).- Space: O(n) for the stored shapes, plus O(W·H) for the grid built during a render.
Reference solution
from collections import OrderedDict
from typing import List
def run_canvas_commands(canvas_width: int, canvas_height: int, commands: List[str], command_args: List[List]) -> List:
# shape_id -> (x, y, w, h, fill); iteration order is bottom -> top
shapes = OrderedDict()
def render() -> List[str]:
grid = [['.'] * canvas_width for _ in range(canvas_height)]
for x, y, w, h, fill in shapes.values():
x0 = max(0, x)
y0 = max(0, y)
x1 = min(canvas_width, x + w)
y1 = min(canvas_height, y + h)
if x0 >= x1 or y0 >= y1:
continue
for row in range(y0, y1):
for col in range(x0, x1):
grid[row][col] = fill
return [''.join(row) for row in grid]
results = []
for cmd, args in zip(commands, command_args):
if cmd == "add_rectangle":
shape_id, x, y, w, h, fill = args
if shape_id in shapes or w <= 0 or h <= 0:
results.append(False)
else:
shapes[shape_id] = (x, y, w, h, fill)
results.append(True)
elif cmd == "remove":
results.append(shapes.pop(args[0], None) is not None)
elif cmd == "bring_to_front":
if args[0] in shapes:
shapes.move_to_end(args[0], last=True)
results.append(True)
else:
results.append(False)
elif cmd == "send_to_back":
if args[0] in shapes:
shapes.move_to_end(args[0], last=False)
results.append(True)
else:
results.append(False)
elif cmd == "render":
results.append(render())
return results