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 (default 10 by 6)
  • 0 <= len(operations) == len(arguments) <= 2000
  • -10^6 <= x, y <= 10^6 and -10^6 <= rect_width, rect_height <= 10^6
  • Valid fill strings have len(fill) == 1.
  • Layer mutations (add_rectangle, remove_rectangle, bring_to_front, send_to_back) must run in O(1) average time.

Step-by-step walkthrough

  1. Understand the canvas coordinate system and layer rules

    We are designing a layered ASCII canvas of dimensions width x height (10 x 6 by default, with custom sizes passed in process_ascii_canvas). Coordinates (x, y) place (0, 0) at the upper-left corner: x indexes columns left-to-right (0 <= x < width) and y indexes rows top-to-bottom (0 <= y < height).

    Each method on AsciiCanvas updates 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. Returns False without mutating state if shape_id already exists, width <= 0, height <= 0, or len(fill) != 1.
    • remove_rectangle(shape_id) -> bool: deletes shape_id (freeing the ID for reuse), or returns False if absent.
    • bring_to_front(shape_id) -> bool: moves shape_id to the topmost layer, or returns False if absent.
    • send_to_back(shape_id) -> bool: moves shape_id to the bottommost layer, or returns False if absent.
    • render() -> List[str]: returns height strings of length width, 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.

  2. Why a plain list or eager pixel grid is awkward

    Storing shapes in a plain Python list makes layer operations slow:

    • Checking whether shape_id already exists scans the list in O(n) time.
    • bring_to_front and send_to_back pop from an arbitrary index and shift up to n elements, also costing O(n) time.

    Conversely, maintaining a single live 2D character grid on every edit ("eager rendering") makes add_rectangle easy, but remove_rectangle and send_to_back uncover previously hidden cells — forcing you to search lower layers to figure out what now shows through every uncovered cell.

  3. Key idea: `OrderedDict` for layers + lazy bottom-up rendering

    Separating z-order management from grid rasterization gives O(1) edits and simple rendering:

    1. Z-order stack (OrderedDict): Python's collections.OrderedDict pairs a hash table with a doubly linked list. Keying by shape_id in bottom-to-top order means:
      • testing shape_id in _shapes, inserting on top, and deleting by ID all run in O(1) average time;
      • move_to_end(shape_id, last=True) relinks a node to the top in O(1) time;
      • move_to_end(shape_id, last=False) relinks a node to the bottom in O(1) time.
    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)
    
    1. 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, and AsciiCanvas.

  4. 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) and x1 = min(self.x + self.width, canvas_width)
    • y0 = max(self.y, 0) and y1 = min(self.y + self.height, canvas_height)

    Look at Example 2, where "tag" sits at x = -1, y = 2 with width = 4, height = 4 on a 6 x 4 grid:

    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 away
    

    When a rectangle lies completely off-grid (say x = 20 on a width-6 canvas), x0 = 20 and x1 = 6. Since 20 >= 6, range(20, 6) is empty and writes zero cells without special-case branches — and even a 1,000,000 x 1,000,000 rectangle visits at most canvas_width * canvas_height cells!

    @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
    
  5. Build `LayerStack` with `O(1)` reordering

    LayerStack encapsulates OrderedDict behind domain methods (push_top, remove, move_to_top, move_to_bottom, bottom_to_top). Calling bring_to_front on an already-topmost shape still finds shape_id in _shapes, leaves it at the tail via move_to_end, and returns True.

    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())
    
  6. Build `CanvasRenderer` using the painter's algorithm

    Because Python strings are immutable, we build a height x width 2D 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 lines
    
  7. Wire up `AsciiCanvas` and trace Example 1

    AsciiCanvas.add_rectangle validates duplicate IDs, positive dimensions, and single-character fill before mutating _layers, ensuring rejected calls leave existing state untouched. In process_ascii_canvas, both "remove" (used in Example 2) and "remove_rectangle" dispatch to canvas.remove_rectangle(...).

    Let's trace Example 1 on an 8 x 5 canvas ("p1" at (1, 0) size 4 x 3 fill '#', "p2" at (3, 1) size 4 x 3 fill '@'):

    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:
       .####...
       .####@@.
       .####@@.
       ...@@@@.
       ........
    
  8. 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_front slips a note out from wherever it sits and places it on top; send_to_back tucks it underneath every other note.
  • render captures 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 when render() 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:

  1. add_rectangle("p1", 1, 0, 4, 3, "#") followed by add_rectangle("p2", 3, 1, 4, 3, "@") yields the bottom-to-top order [p1, p2].
  2. On render(), we initialize a 5 x 8 grid of '.', fill "p1" across columns 1..4 and rows 0..2 with '#', and then fill "p2" across columns 3..6 and rows 1..3 with '@' — leaving '@' in the overlap cells (3..4, 1..2).
  3. bring_to_front("p1") relinks "p1" to the tail of the OrderedDict in O(1) time so the stack becomes [p2, p1]; on the next render(), "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 in OrderedDict plus at most one insertion, deletion, or doubly-linked-list relink (move_to_end), independent of n and W * H.
  • Time for render: O(W * H + n + A), bounded by O(n * W * H). Initializing the background visits W * H cells, walking the stack visits n shapes, and each shape writes only its clipped visible slice (A total cell writes).
  • Space: O(n + W * H). LayerStack holds one Rectangle per active shape (O(n)), and render() allocates one H x W character buffer plus the H output 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 = 4 paints columns 0, 1, 2 — and caps work per shape at W * H even when dimensions are 10^6.
  • Completely off-grid shapes: accepted (True) whenever width > 0, height > 0, len(fill) == 1, and shape_id is unused. Clamping produces x0 >= x1 or y0 >= y1, so range runs zero times while the shape remains reorderable and removable.
  • Duplicate shape_id: add_rectangle returns False without changing the existing shape's geometry, fill, or z-order position (as in Example 3).
  • Zero or negative dimensions: rejected with False prior to mutating LayerStack, leaving shape_id free for later use.
  • Unknown shape_id on remove_rectangle, bring_to_front, or send_to_back: returns False and leaves the stack untouched.
  • Promoting the top shape or demoting the bottom shape: returns True and preserves the current z-order.
  • Reusing a deleted shape_id: once remove_rectangle deletes an ID, a subsequent add_rectangle with 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 raising IndexError, 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 filtering 0 <= row < H inside the loop times out on million-unit rectangles.
  • Row-aliasing bug [['.'] * W] * H: repeats the same inner list reference H times, so assigning grid[0][2] = '#' mutates column 2 across every row.
  • Transposing x and y when indexing grid: column x is the second index and row y is the first (grid[y][x], not grid[x][y]).
  • Iterating top-to-bottom while unconditionally overwriting: causes lower layers to overwrite higher layers.
  • Overwriting duplicate keys in OrderedDict: omitting contains(shape_id) would replace an existing shape instead of returning False.

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 W grid on every mutation so render() only joins rows in O(W * H). add_rectangle and bring_to_front simply paint on top, but remove_rectangle and send_to_back must recompute uncovered cells from lower shapes (or store a sorted set of covering layers per cell). Useful only when render() vastly outnumbers mutations.
  • Monotonic integer z-keys: store (z, Rectangle) in a dict, assigning max_z + 1 on bring_to_front and min_z - 1 on send_to_back. Mutations remain O(1), at the cost of sorting in O(n log n) during render().

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 all 3840 * 2160 cells are filled. Pair this with 64 x 64 tile 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() and undo() — push a command onto undo_stack only when execute() returns True, and clear redo_stack on any fresh edit. AddCommand.undo() removes shape_id; RemoveCommand records both the deleted Rectangle and its immediate neighbor in LayerStack so undo() splices it back into its exact prior z-depth; and ReorderCommand records the shape's prior neighbor so undo() restores its original layer position in O(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") then bring_to_front("p2") leaves "p2" on top, whereas the reverse leaves "p1" on top — so writes require a single serialized order. Within one process, guard LayerStack with a mutex (mutual-exclusion lock) or single-writer command queue, and let render() copy bottom_to_top() in O(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's base_version and rejecting or rebasing conflicting updates).

Follow-up questions

Similar questions

More Asana interview questions

All 24 Asana questions →