Layered ASCII Rectangle Canvas Engine
Medium · Software Engineering Fundamentals · Software Engineer · Onsite
Problem Statement
Build an object-oriented 2D character grid engine (AsciiCanvas) of size width columns by height rows (defaulting to 10 by 6) that manages an ordered z-stack of filled ASCII rectangles.
Grid coordinates (x, y) place (0, 0) at the upper-left cell, with column x advancing rightward across [0, width) and row y advancing downward across [0, height). When rendered, cells covered by multiple rectangles display the character of whichever rectangle sits highest in the z-stack, while uncovered cells display '.'.
Implement AsciiCanvas with the following methods:
class AsciiCanvas:
def __init__(self, width: int = 10, height: int = 6) -> None:
"""Create an empty width-by-height grid with '.' as the background character."""
pass
def add_rectangle(self, shape_id: str, x: int, y: int, width: int, height: int, fill: str) -> bool:
"""Push a filled rectangle onto the top of the z-stack.
Return False without changing state if shape_id is already active,
width <= 0, height <= 0, or len(fill) != 1."""
pass
def remove_rectangle(self, shape_id: str) -> bool:
"""Delete shape_id from the z-stack, or return False if absent."""
pass
def bring_to_front(self, shape_id: str) -> bool:
"""Promote shape_id to the topmost z-layer, or return False if absent."""
pass
def send_to_back(self, shape_id: str) -> bool:
"""Demote shape_id to the bottommost z-layer, or return False if absent."""
pass
def render(self) -> List[str]:
"""Return height strings of length width representing the visible grid."""
pass
Rectangles are permitted to extend partly or completely outside [0, width) x [0, height) (including negative coordinates): as long as their dimensions are positive, fill is a single character, and shape_id is unused, they are stored in the z-stack, respond to reordering and deletion, and paint only the cells intersecting [0, width) x [0, height). Removing a shape frees its shape_id for future add_rectangle calls.
In addition, implement the command runner process_ascii_canvas(width: int, height: int, operations: List[str], arguments: List[List]) -> List, which instantiates AsciiCanvas(width, height), executes each operation in operations ("add_rectangle", "remove" or "remove_rectangle", "bring_to_front", "send_to_back", "render") with the matching entry in arguments, and returns the list of results in order. Structure your code with clear separation of concerns (geometry clipping, layer ordering, and rasterization), and be ready to weigh on-demand rasterization against maintaining a live character buffer.
Examples
Example 1
Input:
width = 8, height = 5
operations = ["add_rectangle", "add_rectangle", "render", "bring_to_front", "render"]
arguments = [["p1", 1, 0, 4, 3, "#"], ["p2", 3, 1, 4, 3, "@"], [], ["p1"], []]
Output:
[
True,
True,
[".####...", ".##@@@@.", ".##@@@@.", "...@@@@.", "........"],
True,
[".####...", ".####@@.", ".####@@.", "...@@@@.", "........"]
]
Walk-through: "p1" covers columns 1..4, rows 0..2 with '#', and "p2" covers columns 3..6, rows 1..3 with '@' on top of "p1". On the first render, '@' wins the overlap at columns 3..4, rows 1..2. Calling bring_to_front("p1") promotes "p1" above "p2", so '#' wins that overlap on the second render.
Example 2
Input:
width = 6, height = 4
operations = ["add_rectangle", "render", "remove", "remove", "render"]
arguments = [["tag", -1, 2, 4, 4, "*"], [], ["ghost"], ["tag"], []]
Output:
[
True,
["......", "......", "***...", "***..."],
False,
True,
["......", "......", "......", "......"]
]
Walk-through: "tag" spans unclipped columns [-1, 3) and rows [2, 6), which clip against the 6 x 4 grid to columns 0..2 and rows 2..3. Removing unknown ID "ghost" returns False, while removing "tag" returns True and restores the blank grid.
Example 3
Input:
width = 4, height = 3
operations = ["add_rectangle", "add_rectangle", "add_rectangle", "send_to_back", "render"]
arguments = [["bg", 0, 0, 4, 3, "+"], ["box", 1, 1, 2, 1, "X"], ["box", 0, 0, 1, 1, "Z"], ["box"], []]
Output:
[True, True, False, True, ["++++", "++++", "++++"]]
Walk-through: Adding "bg" and "box" succeeds, whereas the second "box" call is rejected (False) without altering the existing "box". Sending "box" to the back places it underneath the full-canvas "bg" rectangle, so rendering produces all '+' characters.
Constraints
1 <= width, height <= 200(default10by6)0 <= len(operations) == len(arguments) <= 2000-10^6 <= x, y <= 10^6and-10^6 <= rect_width, rect_height <= 10^6- Valid
fillstrings havelen(fill) == 1. - Layer mutations (
add_rectangle,remove_rectangle,bring_to_front,send_to_back) must run inO(1)average time.
Step-by-step walkthrough
Understand the canvas coordinate system and layer rules
We are designing a layered ASCII canvas of dimensions
width x height(10 x 6by default, with custom sizes passed inprocess_ascii_canvas). Coordinates(x, y)place(0, 0)at the upper-left corner:xindexes columns left-to-right (0 <= x < width) andyindexes rows top-to-bottom (0 <= y < height).Each method on
AsciiCanvasupdates a z-ordered stack of filled rectangles or rasterizes the visible grid:add_rectangle(shape_id, x, y, width, height, fill) -> bool: inserts a new rectangle at the top of the stack. ReturnsFalsewithout mutating state ifshape_idalready exists,width <= 0,height <= 0, orlen(fill) != 1.remove_rectangle(shape_id) -> bool: deletesshape_id(freeing the ID for reuse), or returnsFalseif absent.bring_to_front(shape_id) -> bool: movesshape_idto the topmost layer, or returnsFalseif absent.send_to_back(shape_id) -> bool: movesshape_idto the bottommost layer, or returnsFalseif absent.render() -> List[str]: returnsheightstrings of lengthwidth, displaying the topmost rectangle covering each cell (or'.'where uncovered).
Rectangles may lie partially or completely outside
[0, width) x [0, height)— they still live in the z-stack, respond to reordering and deletion, and draw only the cells falling inside the canvas.Why a plain list or eager pixel grid is awkward
Storing shapes in a plain Python
listmakes layer operations slow:- Checking whether
shape_idalready exists scans the list inO(n)time. bring_to_frontandsend_to_backpop from an arbitrary index and shift up tonelements, also costingO(n)time.
Conversely, maintaining a single live 2D character grid on every edit ("eager rendering") makes
add_rectangleeasy, butremove_rectangleandsend_to_backuncover previously hidden cells — forcing you to search lower layers to figure out what now shows through every uncovered cell.- Checking whether
Key idea: `OrderedDict` for layers + lazy bottom-up rendering
Separating z-order management from grid rasterization gives
O(1)edits and simple rendering:- Z-order stack (
OrderedDict): Python'scollections.OrderedDictpairs a hash table with a doubly linked list. Keying byshape_idin bottom-to-top order means:- testing
shape_id in _shapes, inserting on top, and deleting by ID all run inO(1)average time; move_to_end(shape_id, last=True)relinks a node to the top inO(1)time;move_to_end(shape_id, last=False)relinks a node to the bottom inO(1)time.
- testing
Layer order inside OrderedDict: head (bottom) tail (top) +------------+ +------------+ +------------+ | shape "p1" | <===> | shape "p2" | <===> | shape "p3" | +------------+ +------------+ +------------+ move_to_end("p1", last=True) --> [p2] <===> [p3] <===> [p1] ("p1" is now on top) move_to_end("p3", last=False) --> [p3] <===> [p2] <===> [p1] ("p3" is now at bottom)- On-demand rendering (painter's algorithm):
render()allocates a fresh'.'grid and paints rectangles from bottom to top, so higher layers naturally overwrite lower layers on overlapping cells.
We organize these responsibilities into four focused classes:
Rectangle,LayerStack,CanvasRenderer, andAsciiCanvas.- Z-order stack (
Model `Rectangle` and coordinate clipping
A rectangle at
(x, y)of size(width, height)covers columns[x, x + width)and rows[y, y + height). To clip those intervals against[0, canvas_width) x [0, canvas_height)before touching pixels, intersect each axis:x0 = max(self.x, 0)andx1 = min(self.x + self.width, canvas_width)y0 = max(self.y, 0)andy1 = min(self.y + self.height, canvas_height)
Look at Example 2, where
"tag"sits atx = -1, y = 2withwidth = 4, height = 4on a6 x 4grid:Unclipped x: [-1, 3) intersect [0, 6) --> visible columns [0, 3) (cols 0, 1, 2) Unclipped y: [ 2, 6) intersect [0, 4) --> visible rows [2, 4) (rows 2, 3) x=-1 0 6 +------+ 0 |......| 1 |......| y=2 *|***...| <-- clipped inside 6x4 grid 3 *|***...| +------+ **** <-- rows 4, 5 clipped awayWhen a rectangle lies completely off-grid (say
x = 20on a width-6 canvas),x0 = 20andx1 = 6. Since20 >= 6,range(20, 6)is empty and writes zero cells without special-case branches — and even a1,000,000 x 1,000,000rectangle visits at mostcanvas_width * canvas_heightcells!@dataclass(frozen=True) class Rectangle: """Immutable filled rectangle; (x, y) is the top-left column and row.""" shape_id: str x: int y: int width: int height: int fill: str def visible_bounds(self, canvas_width: int, canvas_height: int) -> Tuple[int, int, int, int]: """Clip [x, x + width) and [y, y + height) against [0, canvas_width) and [0, canvas_height).""" # Clamp start coordinates up to 0 and end coordinates down to canvas dimensions. # If the shape lies completely outside the canvas, x0 >= x1 or y0 >= y1, # so range(x0, x1) or range(y0, y1) safely yields zero iterations. x0 = max(self.x, 0) x1 = min(self.x + self.width, canvas_width) y0 = max(self.y, 0) y1 = min(self.y + self.height, canvas_height) return x0, x1, y0, y1Build `LayerStack` with `O(1)` reordering
LayerStackencapsulatesOrderedDictbehind domain methods (push_top,remove,move_to_top,move_to_bottom,bottom_to_top). Callingbring_to_fronton an already-topmost shape still findsshape_idin_shapes, leaves it at the tail viamove_to_end, and returnsTrue.class LayerStack: """Maintains shapes from bottom layer to top layer with O(1) lookup and reordering.""" def __init__(self) -> None: # _shapes: OrderedDict[shape_id, Rectangle] ordered from bottom (first) to top (last). # Internally backed by a hash table + doubly linked list, giving O(1) moves to either end. self._shapes: "OrderedDict[str, Rectangle]" = OrderedDict() def contains(self, shape_id: str) -> bool: return shape_id in self._shapes def push_top(self, rect: Rectangle) -> None: # Assigning a brand-new key in OrderedDict appends it at the end (the topmost layer). self._shapes[rect.shape_id] = rect def remove(self, shape_id: str) -> bool: if shape_id not in self._shapes: return False del self._shapes[shape_id] return True def move_to_top(self, shape_id: str) -> bool: if shape_id not in self._shapes: return False # last=True relinks the node to the tail (topmost layer) in O(1) time. self._shapes.move_to_end(shape_id, last=True) return True def move_to_bottom(self, shape_id: str) -> bool: if shape_id not in self._shapes: return False # last=False relinks the node to the head (bottommost layer) in O(1) time. self._shapes.move_to_end(shape_id, last=False) return True def bottom_to_top(self) -> List[Rectangle]: return list(self._shapes.values())Build `CanvasRenderer` using the painter's algorithm
Because Python strings are immutable, we build a
height x width2D list of'.'characters first, making sure to allocate an independent list per row (avoiding[['.'] * width] * height, which aliases all rows to one list). Then we paint each shape's clipped[y0, y1) x [x0, x1)slice in bottom-to-top order and join each row into a string.class CanvasRenderer: """Rasterizes a bottom-to-top list of rectangles into rows of ASCII characters.""" def __init__(self, width: int, height: int, background: str = BACKGROUND) -> None: self.width = width self.height = height self.background = background def render(self, shapes_bottom_to_top: List[Rectangle]) -> List[str]: # grid: 2D list of size height x width; grid[row][col] holds one character. # Build a separate list per row so rows never share the same list reference. grid: List[List[str]] = [] for _ in range(self.height): grid.append([self.background] * self.width) # Painter's algorithm: paint from bottom layer up to top layer so higher # shapes naturally overwrite lower shapes wherever they overlap. for rect in shapes_bottom_to_top: x0, x1, y0, y1 = rect.visible_bounds(self.width, self.height) for row in range(y0, y1): for col in range(x0, x1): grid[row][col] = rect.fill lines: List[str] = [] for row in grid: lines.append("".join(row)) return linesWire up `AsciiCanvas` and trace Example 1
AsciiCanvas.add_rectanglevalidates duplicate IDs, positive dimensions, and single-characterfillbefore mutating_layers, ensuring rejected calls leave existing state untouched. Inprocess_ascii_canvas, both"remove"(used in Example 2) and"remove_rectangle"dispatch tocanvas.remove_rectangle(...).Let's trace Example 1 on an
8 x 5canvas ("p1"at(1, 0)size4 x 3fill'#',"p2"at(3, 1)size4 x 3fill'@'):1) add_rectangle("p1", ...) then add_rectangle("p2", ...) --> stack bottom-to-top: [p1, p2] Paint p1 first, then p2 overwrites overlap cols 3..4, rows 1..2: .####... .##@@@@. .##@@@@. ...@@@@. ........ 2) bring_to_front("p1") --> stack bottom-to-top: [p2, p1] Paint p2 first, then p1 overwrites overlap cols 3..4, rows 1..2: .####... .####@@. .####@@. ...@@@@. ........Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple from collections import OrderedDict from dataclasses import dataclass BACKGROUND = "." @dataclass(frozen=True) class Rectangle: """Immutable filled rectangle; (x, y) is the top-left column and row.""" shape_id: str x: int y: int width: int height: int fill: str def visible_bounds(self, canvas_width: int, canvas_height: int) -> Tuple[int, int, int, int]: """Clip [x, x + width) and [y, y + height) against [0, canvas_width) and [0, canvas_height).""" # Clamp start coordinates up to 0 and end coordinates down to canvas dimensions. # If the shape lies completely outside the canvas, x0 >= x1 or y0 >= y1, # so range(x0, x1) or range(y0, y1) safely yields zero iterations. x0 = max(self.x, 0) x1 = min(self.x + self.width, canvas_width) y0 = max(self.y, 0) y1 = min(self.y + self.height, canvas_height) return x0, x1, y0, y1 class LayerStack: """Maintains shapes from bottom layer to top layer with O(1) lookup and reordering.""" def __init__(self) -> None: # _shapes: OrderedDict[shape_id, Rectangle] ordered from bottom (first) to top (last). # Internally backed by a hash table + doubly linked list, giving O(1) moves to either end. self._shapes: "OrderedDict[str, Rectangle]" = OrderedDict() def contains(self, shape_id: str) -> bool: return shape_id in self._shapes def push_top(self, rect: Rectangle) -> None: # Assigning a brand-new key in OrderedDict appends it at the end (the topmost layer). self._shapes[rect.shape_id] = rect def remove(self, shape_id: str) -> bool: if shape_id not in self._shapes: return False del self._shapes[shape_id] return True def move_to_top(self, shape_id: str) -> bool: if shape_id not in self._shapes: return False # last=True relinks the node to the tail (topmost layer) in O(1) time. self._shapes.move_to_end(shape_id, last=True) return True def move_to_bottom(self, shape_id: str) -> bool: if shape_id not in self._shapes: return False # last=False relinks the node to the head (bottommost layer) in O(1) time. self._shapes.move_to_end(shape_id, last=False) return True def bottom_to_top(self) -> List[Rectangle]: return list(self._shapes.values()) class CanvasRenderer: """Rasterizes a bottom-to-top list of rectangles into rows of ASCII characters.""" def __init__(self, width: int, height: int, background: str = BACKGROUND) -> None: self.width = width self.height = height self.background = background def render(self, shapes_bottom_to_top: List[Rectangle]) -> List[str]: # grid: 2D list of size height x width; grid[row][col] holds one character. # Build a separate list per row so rows never share the same list reference. grid: List[List[str]] = [] for _ in range(self.height): grid.append([self.background] * self.width) # Painter's algorithm: paint from bottom layer up to top layer so higher # shapes naturally overwrite lower shapes wherever they overlap. for rect in shapes_bottom_to_top: x0, x1, y0, y1 = rect.visible_bounds(self.width, self.height) for row in range(y0, y1): for col in range(x0, x1): grid[row][col] = rect.fill lines: List[str] = [] for row in grid: lines.append("".join(row)) return lines class AsciiCanvas: """Public facade coordinating validation, layer ordering, and rendering.""" def __init__(self, width: int = 10, height: int = 6) -> None: self._layers = LayerStack() self._renderer = CanvasRenderer(width, height) def add_rectangle(self, shape_id: str, x: int, y: int, width: int, height: int, fill: str) -> bool: # Validate all rules BEFORE mutating _layers so invalid calls leave state untouched. if self._layers.contains(shape_id): return False if width <= 0 or height <= 0: return False if len(fill) != 1: return False rect = Rectangle(shape_id, x, y, width, height, fill) self._layers.push_top(rect) return True def remove_rectangle(self, shape_id: str) -> bool: return self._layers.remove(shape_id) def bring_to_front(self, shape_id: str) -> bool: return self._layers.move_to_top(shape_id) def send_to_back(self, shape_id: str) -> bool: return self._layers.move_to_bottom(shape_id) def render(self) -> List[str]: return self._renderer.render(self._layers.bottom_to_top()) def process_ascii_canvas(width: int, height: int, operations: List[str], arguments: List[List]) -> List: # Judge adapter: replay each command against one AsciiCanvas and collect return values. canvas = AsciiCanvas(width, height) results: List[Any] = [] for op, args in zip(operations, arguments): if op == "add_rectangle": shape_id, x, y, rect_width, rect_height, fill = args results.append(canvas.add_rectangle(shape_id, x, y, rect_width, rect_height, fill)) elif op in ("remove", "remove_rectangle"): # Judge command lists pass "remove" to invoke AsciiCanvas.remove_rectangle. results.append(canvas.remove_rectangle(args[0])) elif op == "bring_to_front": results.append(canvas.bring_to_front(args[0])) elif op == "send_to_back": results.append(canvas.send_to_back(args[0])) elif op == "render": results.append(canvas.render()) else: raise ValueError(f"unknown operation: {op}") return results✅ Submit now — all tests should pass.
Intuition & how it works
Picture sticking colored rectangular sticky notes onto a corkboard:
- Adding a rectangle places a fresh note at the very top of the pile.
bring_to_frontslips a note out from wherever it sits and places it on top;send_to_backtucks it underneath every other note.rendercaptures what you see looking straight down. Rather than erasing and patching individual cells every time a note moves, we use lazy rendering (also called on-demand rasterization, meaning edits only update the ordered collection of shapes and convert them into a 2D character grid only whenrender()runs). Concretely, we apply the painter's algorithm — drawing shapes from bottom layer to top layer so upper shapes naturally overwrite lower ones on overlapping cells.
Two naive designs run into trouble. Storing shapes in a plain Python list forces O(n) scans and element shifts on every lookup, deletion, or z-order move instead of O(1). Conversely, eagerly maintaining a single 2D character buffer on every mutation makes remove_rectangle and send_to_back awkward, because lifting a shape off a cell exposes whichever lower shape was hidden underneath it.
To achieve O(1) mutations, we store layers in Python's OrderedDict — a hash table coupled with a doubly linked list (a chain of nodes carrying both forward and backward pointers so any entry can be unlinked and moved to either end in O(1) time). Walk through Example 1 on an 8 x 5 grid:
add_rectangle("p1", 1, 0, 4, 3, "#")followed byadd_rectangle("p2", 3, 1, 4, 3, "@")yields the bottom-to-top order[p1, p2].- On
render(), we initialize a5 x 8grid of'.', fill"p1"across columns1..4and rows0..2with'#', and then fill"p2"across columns3..6and rows1..3with'@'— leaving'@'in the overlap cells(3..4, 1..2). bring_to_front("p1")relinks"p1"to the tail of theOrderedDictinO(1)time so the stack becomes[p2, p1]; on the nextrender(),"p1"paints last and wins the overlap with'#'.
Complexity
Let n be the active shape count, W x H be the grid dimensions, and A be the sum of clipped visible cell areas across all n shapes (A <= n * W * H).
- Time for
add_rectangle,remove_rectangle,bring_to_front,send_to_back:O(1)average. Each call performs one hash lookup inOrderedDictplus at most one insertion, deletion, or doubly-linked-list relink (move_to_end), independent ofnandW * H. - Time for
render:O(W * H + n + A), bounded byO(n * W * H). Initializing the background visitsW * Hcells, walking the stack visitsnshapes, and each shape writes only its clipped visible slice (Atotal cell writes). - Space:
O(n + W * H).LayerStackholds oneRectangleper active shape (O(n)), andrender()allocates oneH x Wcharacter buffer plus theHoutput strings (O(W * H)).
Edge cases
- Partially off-grid shapes: clipping (intersecting
[x, x + width)with[0, W)and[y, y + height)with[0, H)before looping) paints only in-bounds cells — in Example 2,x = -1, width = 4paints columns0, 1, 2— and caps work per shape atW * Heven when dimensions are10^6. - Completely off-grid shapes: accepted (
True) wheneverwidth > 0,height > 0,len(fill) == 1, andshape_idis unused. Clamping producesx0 >= x1ory0 >= y1, sorangeruns zero times while the shape remains reorderable and removable. - Duplicate
shape_id:add_rectanglereturnsFalsewithout changing the existing shape's geometry, fill, or z-order position (as in Example 3). - Zero or negative dimensions: rejected with
Falseprior to mutatingLayerStack, leavingshape_idfree for later use. - Unknown
shape_idonremove_rectangle,bring_to_front, orsend_to_back: returnsFalseand leaves the stack untouched. - Promoting the top shape or demoting the bottom shape: returns
Trueand preserves the current z-order. - Reusing a deleted
shape_id: onceremove_rectangledeletes an ID, a subsequentadd_rectanglewith that ID succeeds at the top layer.
Common mistakes
- Skipping clipping on negative coordinates: in Python,
grid[-1]silently indexes the final row rather than raisingIndexError, wrapping off-grid shapes onto the opposite edge! - Testing bounds inside nested pixel loops instead of clamping first: iterating
range(rect.y, rect.y + rect.height)and filtering0 <= row < Hinside the loop times out on million-unit rectangles. - Row-aliasing bug
[['.'] * W] * H: repeats the same inner list referenceHtimes, so assigninggrid[0][2] = '#'mutates column2across every row. - Transposing
xandywhen indexinggrid: columnxis the second index and rowyis the first (grid[y][x], notgrid[x][y]). - Iterating top-to-bottom while unconditionally overwriting: causes lower layers to overwrite higher layers.
- Overwriting duplicate keys in
OrderedDict: omittingcontains(shape_id)would replace an existing shape instead of returningFalse.
Alternative approaches
- Lazy rasterization on
render()(our approach):O(1)edits, compact state, and one source of truth (LayerStack). Best when edits are frequent or grid dimensions are modest. - Eager character buffer: keep an updated
H x Wgrid on every mutation sorender()only joins rows inO(W * H).add_rectangleandbring_to_frontsimply paint on top, butremove_rectangleandsend_to_backmust recompute uncovered cells from lower shapes (or store a sorted set of covering layers per cell). Useful only whenrender()vastly outnumbers mutations. - Monotonic integer
z-keys: store(z, Rectangle)in adict, assigningmax_z + 1onbring_to_frontandmin_z - 1onsend_to_back. Mutations remainO(1), at the cost of sorting inO(n log n)duringrender().
Follow-up questions
- Suppose the grid grows to ultra-high resolution (such as 3840 by 2160) and holds thousands of stacked shapes where lower ones are mostly hidden — how can you speed up frame generation? Bottom-to-top painting wastes work overwriting cells that upper shapes later hide. Instead, traverse top-to-bottom so each cell is written at most once, using a per-row disjoint-set (union-find) jump array — parent pointers with path compression that leap directly across already-painted column runs in nearly
O(1)amortized time, skipping fully occluded rectangles almost instantly and stopping early once all3840 * 2160cells are filled. Pair this with64 x 64tile caching so an edit only invalidates and re-rasterizes dirty tiles (cached tiles overlapping the modified shape's clipped bounding box). - How would you design multi-step undo and redo on top of this engine using command objects? Under the Command pattern — an object-oriented design that encapsulates each state-changing action as an object exposing
execute()andundo()— push a command ontoundo_stackonly whenexecute()returnsTrue, and clearredo_stackon any fresh edit.AddCommand.undo()removesshape_id;RemoveCommandrecords both the deletedRectangleand its immediate neighbor inLayerStacksoundo()splices it back into its exact prior z-depth; andReorderCommandrecords the shape's prior neighbor soundo()restores its original layer position inO(1)time via a custom doubly linked list + hash map. - What concurrency controls are needed when several users submit edits and render requests to the same canvas simultaneously? Z-order mutations do not commute —
bring_to_front("p1")thenbring_to_front("p2")leaves"p2"on top, whereas the reverse leaves"p1"on top — so writes require a single serialized order. Within one process, guardLayerStackwith a mutex (mutual-exclusion lock) or single-writer command queue, and letrender()copybottom_to_top()inO(n)under the lock before rasterizing pixels outside the lock so renders never stall incoming edits. Across networked clients, assign monotonic server sequence numbers to operations and apply optimistic concurrency control (attaching the client'sbase_versionand rejecting or rebasing conflicting updates).
Follow-up questions
- Suppose the grid grows to ultra-high resolution (such as 3840 by 2160) and holds thousands of stacked shapes where lower ones are mostly hidden — how can you speed up frame generation?
- How would you design multi-step undo and redo on top of this engine using command objects?
- What concurrency controls are needed when several users submit edits and render requests to the same canvas simultaneously?
Similar questions
- Configurable 2048 Sliding-Tile Engine
- Testable 2048 Grid Engine
- Architecting a Pluggable Animal-Chess Engine
- Complexity Analysis plus Jigsaw and 2048 Game Design
- Heavy-Hitter IPv4 Addresses Under Tight Memory
- Asymmetric Cats and Rabbits Grid Engine
More Asana interview questions
- Complexity Analysis plus Jigsaw and 2048 Game Design Medium
- Architect a Scalable Microblogging Platform Medium
- Engineering Behavioral Prompts: Impact, Mentorship, Disagreement, and Clarity Medium Pro
- Select K Nearest Coordinates to the Origin Medium Pro
- Multi-Line Banner Glyph Renderer Medium Pro
- Asymmetric Cats and Rabbits Grid Engine Medium Pro
- Assemble a Rectangular Edge-Matching Tile Puzzle Medium Pro
- Two-Player Chess Engine and Legal Move Validator Medium Pro
- Cross-Team Collaboration: Delivering Engineering Projects Across Org Boundaries Medium Pro
- K Closest Numbers to a Target in a Sorted Array Medium Pro