Paint Clipped Rectangles on a Character Grid

Medium · Coding & Algorithms · Software Engineer · Onsite

Problem Statement

Implement render_canvas(width, height, rectangles) to paint a sequence of axis-aligned rectangles onto a 2D character grid and return the final image as a list of height strings, each of exact length width.

The grid uses zero-based coordinates where column 0 through width - 1 run left to right and row 0 through height - 1 run top to bottom. Every grid cell starts as a space character (' '), and all trailing spaces on every row must be preserved in the returned strings.

Each element of rectangles has the form [x, y, w, h, border_char, fill_char]:

  • (x, y) specifies the top-left corner at column x and row y.
  • w and h give the horizontal width (spanning columns x through x + w - 1) and vertical height (spanning rows y through y + h - 1).
  • Any cell lying on the outer perimeter of the full unclipped rectangle (col == x, col == x + w - 1, row == y, or row == y + h - 1) is drawn with border_char.
  • Any cell strictly inside that perimeter is drawn with fill_char. When w == 1 or h == 1, the rectangle has no interior cells, so every cell of the shape uses border_char.

Rectangles are processed sequentially from rectangles[0] onward; whenever a later rectangle overlaps cells painted earlier, the new character overwrites what was there. A rectangle's coordinates may place part or all of it outside [0, width - 1] x [0, height - 1]. Out-of-bounds cells are ignored safely, while visible cells still determine perimeter vs. interior status from the rectangle's original unclipped bounds rather than from the grid edge.

Examples

Example 1

Input: width = 6, height = 5, rectangles = [[1, 1, 4, 3, '*', '-']]

Output: [' ', ' **** ', ' *--* ', ' **** ', ' ']


 **** 
 *--* 
 **** 

Explanation: The 4 x 3 box covers columns 1..4 and rows 1..3. Rows 1 and 3 are top and bottom borders ('*'), row 2 has left/right border cells at columns 1 and 4 with '-' inside at columns 2..3, and column 5 remains a trailing space on every row.

Example 2

Input: width = 6, height = 5, rectangles = [[0, 0, 4, 4, '+', '.'], [2, 1, 4, 3, '=', '~']]

Output: ['++++ ', '+.====', '+.=~~=', '++====', ' ']

++++  
+.====
+.=~~=
++====

Explanation: First, [0, 0, 4, 4, '+', '.'] fills columns 0..3 and rows 0..3. Next, [2, 1, 4, 3, '=', '~'] paints columns 2..5 and rows 1..3, overwriting the right half of the first box while leaving its non-overlapping left portion intact.

Example 3

Input: width = 5, height = 4, rectangles = [[-1, -2, 4, 5, '#', ':'], [1, 2, 5, 1, '-', 'x']]

Output: ['::# ', '::# ', '#----', ' ']

::#  
::#  
#----

Explanation: The first rectangle spans unclipped columns -1..2 and rows -2..2. Its top border (row = -2) and left border (col = -1) fall outside the grid, so visible cells (0, 0) and (0, 1) on rows 0 and 1 stay interior ':' while col = 2 and row = 2 draw '#'. The second rectangle has height 1 across columns 1..5 on row 2; it clips to columns 1..4 and overwrites those cells with border character '-'.

Constraints

  • 0 <= width, height <= 1000
  • width * height <= 10^6
  • 1 <= w, h <= 1000
  • x and y are integers and may be negative, zero, or larger than the grid dimensions.
  • border_char and fill_char are single printable ASCII characters.

Step-by-step walkthrough

  1. Understand coordinates, borders, and overlaps

    We start with a blank ASCII canvas of width columns (0 .. width - 1) and height rows (0 .. height - 1), initially filled with space characters ' '. Each rectangle (x, y, w, h, border_char, fill_char) has its upper-left corner at column x, row y, spans w columns (x .. x + w - 1) and h rows (y .. y + h - 1), uses border_char on its outermost ring, and uses fill_char strictly inside:

    4 x 3 rectangle ('*', '-'):     5 x 1 thin rectangle ('-', 'x'):
      ****  <- top border (y)        -----  <- y == orig_bottom, all border!
      *--*  <- interior row          (no interior rows left, so 'x' never appears)
      ****  <- bottom border (y + h - 1)
    

    Three rules govern tricky inputs:

    • Input-order overwrite: rectangles are painted in list order, so a later rectangle replaces whatever character was previously in any overlapping cell.
    • Off-canvas coordinates: x or y can be negative, and x + w or y + h can exceed the canvas size; only the part landing inside the canvas is drawn.
    • Exact row width: the output has height strings of length width, keeping all trailing spaces.
  2. Brute force and where it struggles

    The simplest mental model visits every cell (r, c) of the full w x h rectangle, checks whether (r, c) lies inside the canvas, and writes border_char or fill_char:

    for r in range(y, y + h):
        for c in range(x, x + w):
            if 0 <= r < height and 0 <= c < width:
                on_border = (r == y or r == y + h - 1 or c == x or c == x + w - 1)
                canvas[r][c] = border_char if on_border else fill_char
    

    This produces the right answer, and tests.py uses it as a randomized oracle. However, it loops over cells that sit completely off-canvas, and on a 1,000 x 1,000 canvas (10^6 cells) running millions of inner-loop Python iterations per rectangle adds heavy interpreter overhead.

  3. Key insight: clip the loop bounds, keep the original border coordinates

    Clipping means intersecting a rectangle's column and row intervals with the canvas intervals [0, width - 1] and [0, height - 1] before visiting any cells:

    Original rectangle:  columns [x .. orig_right]     where orig_right  = x + w - 1
                         rows    [y .. orig_bottom]    where orig_bottom = y + h - 1
    
    Visible intersection:
      col_start = max(x, 0),   col_end = min(orig_right, width - 1)
      row_start = max(y, 0),   row_end = min(orig_bottom, height - 1)
    

    Watch out for a classic trap: a clipped edge is not a rectangle border. Suppose we draw (2, 2, 5, 5, '#', '.') on a 4 x 4 canvas:

       col: 0 1 2 3 | 4 5 6  (off canvas)
    row 0:          |
    row 1:          |
    row 2:      # # | # # #   <- r = 2 (original top border)
    row 3:      # . | . . #   <- r = 3: cell (3, 3) is '.' (interior!), NOT '#'
           ---------+------
    row 4:      # . | . . #   (off canvas)
    

    Even though column 3 and row 3 are the last visible positions on the 4 x 4 canvas (col_end = 3, row_end = 3), the rectangle's real right and bottom borders sit out at column 6 and row 6. Therefore:

    • Clipped bounds (row_start .. row_end, col_start .. col_end) decide which cells we touch.
    • Original edges (x, orig_right, y, orig_bottom) decide whether a touched cell is border or fill.
  4. Code the rectangle clipping

    Let's start draw_rectangle by computing the original inclusive end coordinates and intersecting them with the canvas. Notice two safety wins we get immediately:

    1. Clamping with max(x, 0) and max(y, 0) blocks negative numbers, which in Python would otherwise wrap around (row[-1] silently mutates the last column!).
    2. Checking col_start > col_end or row_start > row_end catches both off-screen rectangles and degenerate canvases (width == 0 or height == 0, where width - 1 == -1).
    def draw_rectangle(canvas: List[List[str]], width: int, height: int, rect: List[Any]) -> None:
        # Unpack rectangle: (x, y) is upper-left (col, row); w is width; h is height.
        x, y, w, h, border_char, fill_char = rect
    
        # Phase 1: Compute inclusive right and bottom edges of the ORIGINAL unclipped rectangle.
        # Subtract 1 because starting at x with width w spans columns x, x + 1, ..., x + w - 1.
        orig_right = x + w - 1
        orig_bottom = y + h - 1
    
        # Phase 2: Clip the rectangle's column and row ranges to the canvas [0..width-1] x [0..height-1].
        # Clamping at 0 also prevents negative coordinates from wrapping around in Python list indexing.
        col_start = max(x, 0)
        col_end = min(orig_right, width - 1)
        row_start = max(y, 0)
        row_end = min(orig_bottom, height - 1)
    
        # Empty intersection means the rectangle misses the canvas (or width/height is 0).
        if col_start > col_end or row_start > row_end:
            return
    
  5. Paint each visible row with slice assignment

    For each visible row r from row_start to row_end, every cell in col_start .. col_end follows one of two simple patterns:

    • Top or bottom border row (r == y or r == orig_bottom): the entire visible horizontal span is border_char.
    • Interior row: write fill_char across the entire visible span in a single slice assignment, then overwrite row_cells[x] if the original left border x lies inside [col_start, col_end], and overwrite row_cells[orig_right] if the original right border orig_right lies inside [col_start, col_end].

    Thin rectangles work without any special case: h == 1 has y == orig_bottom (hit by the first branch), and w == 1 has x == orig_right (so the stamp overwrites the single cell with border_char).

    def draw_rectangle(canvas: List[List[str]], width: int, height: int, rect: List[Any]) -> None:
        x, y, w, h, border_char, fill_char = rect
        orig_right = x + w - 1
        orig_bottom = y + h - 1
    
        col_start = max(x, 0)
        col_end = min(orig_right, width - 1)
        row_start = max(y, 0)
        row_end = min(orig_bottom, height - 1)
        if col_start > col_end or row_start > row_end:
            return
    
        # Phase 3: Paint each visible row, testing borders against ORIGINAL edges (x, y, orig_right, orig_bottom)
        # so that an edge cut off by the canvas boundary does not become a fake border.
        visible_width = col_end - col_start + 1
        for r in range(row_start, row_end + 1):
            row_cells = canvas[r]
            if r == y or r == orig_bottom:
                # Original top or bottom edge: every visible cell in this row is border.
                row_cells[col_start:col_end + 1] = [border_char] * visible_width
            else:
                # Interior row: fill the visible span first, then stamp left/right borders if visible.
                row_cells[col_start:col_end + 1] = [fill_char] * visible_width
                if col_start <= x <= col_end:
                    row_cells[x] = border_char
                if col_start <= orig_right <= col_end:
                    row_cells[orig_right] = border_char
    
  6. Initialize the canvas, draw in order, and trace Example 3

    Because Python str objects are immutable, we represent the canvas as height separate lists of width spaces ([" "] * width inside a loop so rows never share a single list), draw each rectangle in order, and "".join(...) each row at the end to preserve trailing spaces:

    def render_canvas(width: int, height: int, rectangles: List[List]) -> List[str]:
        # canvas: height x width grid of single-character strings, initialized to spaces ' '.
        # Allocate each row list separately so rows do not share the same underlying list.
        canvas: List[List[str]] = []
        for _ in range(height):
            canvas.append([" "] * width)
    
        # Draw in input order so later rectangles naturally overwrite earlier ones on overlap.
        for rect in rectangles:
            draw_rectangle(canvas, width, height, rect)
    
        # Join each row of width characters without stripping so trailing spaces are preserved.
        rendered_rows: List[str] = []
        for row_cells in canvas:
            rendered_rows.append("".join(row_cells))
        return rendered_rows
    

    Let's trace Example 3 (width = 5, height = 4) with [-1, -2, 4, 5, '#', ':'] followed by [1, 2, 5, 1, '-', 'x']:

    1) Draw [-1, -2, 4, 5, '#', ':']:
       Original: cols -1..2 (x=-1, orig_right=2), rows -2..2 (y=-2, orig_bottom=2)
       Clipped:  cols  0..2,                      rows  0..2
       - r = 0 (interior; x=-1 off-canvas, orig_right=2 visible): "::#  "
       - r = 1 (interior; x=-1 off-canvas, orig_right=2 visible): "::#  "
       - r = 2 (r == orig_bottom == 2 -> all border):             "###  "
       - r = 3 (untouched):                                       "     "
    
    2) Draw [1, 2, 5, 1, '-', 'x'] on top:
       Original: cols 1..5, row 2..2 (y == orig_bottom == 2 -> single border row!)
       Clipped:  cols 1..4, row 2..2
       - r = 0: "::#  "
       - r = 1: "::#  "
       - r = 2: "#----"   (cols 1..4 overwritten with '-')
       - r = 3: "     "
    
  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def draw_rectangle(canvas: List[List[str]], width: int, height: int, rect: List[Any]) -> None:
        # Unpack rectangle: (x, y) is upper-left (col, row); w is width; h is height.
        x, y, w, h, border_char, fill_char = rect
    
        # Phase 1: Compute inclusive right and bottom edges of the ORIGINAL unclipped rectangle.
        # Subtract 1 because starting at x with width w spans columns x, x + 1, ..., x + w - 1.
        orig_right = x + w - 1
        orig_bottom = y + h - 1
    
        # Phase 2: Clip the rectangle's column and row ranges to the canvas [0..width-1] x [0..height-1].
        # Clamping at 0 also prevents negative coordinates from wrapping around in Python list indexing.
        col_start = max(x, 0)
        col_end = min(orig_right, width - 1)
        row_start = max(y, 0)
        row_end = min(orig_bottom, height - 1)
    
        # Empty intersection means the rectangle misses the canvas (or width/height is 0).
        if col_start > col_end or row_start > row_end:
            return
    
        # Phase 3: Paint each visible row, testing borders against ORIGINAL edges (x, y, orig_right, orig_bottom)
        # so that an edge cut off by the canvas boundary does not become a fake border.
        visible_width = col_end - col_start + 1
        for r in range(row_start, row_end + 1):
            row_cells = canvas[r]
            if r == y or r == orig_bottom:
                # Original top or bottom edge: every visible cell in this row is border.
                row_cells[col_start:col_end + 1] = [border_char] * visible_width
            else:
                # Interior row: fill the visible span first, then stamp left/right borders if visible.
                row_cells[col_start:col_end + 1] = [fill_char] * visible_width
                if col_start <= x <= col_end:
                    row_cells[x] = border_char
                if col_start <= orig_right <= col_end:
                    row_cells[orig_right] = border_char
    
    
    def render_canvas(width: int, height: int, rectangles: List[List]) -> List[str]:
        # canvas: height x width grid of single-character strings, initialized to spaces ' '.
        # Allocate each row list separately so rows do not share the same underlying list.
        canvas: List[List[str]] = []
        for _ in range(height):
            canvas.append([" "] * width)
    
        # Draw in input order so later rectangles naturally overwrite earlier ones on overlap.
        for rect in rectangles:
            draw_rectangle(canvas, width, height, rect)
    
        # Join each row of width characters without stripping so trailing spaces are preserved.
        rendered_rows: List[str] = []
        for row_cells in canvas:
            rendered_rows.append("".join(row_cells))
        return rendered_rows
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of placing rectangular paper stickers onto a glass window frame one after another: any part of a sticker hanging past the window frame is trimmed off at the edge, each new sticker covers whatever was underneath it, and if a sticker's outer border hangs past the glass, you still see its inner pattern right up to the window edge rather than a newly drawn border.

Looping over every cell of every full rectangle wastes time on off-screen coordinates, and forgetting to clamp negative indices in Python silently wraps row[-1] around to the right edge of the canvas instead of failing. On the other hand, if you crop a rectangle to fit the canvas and then draw a fresh border around the cropped box, cut-off edges turn into fake borders. Using clipping—intersecting each rectangle's horizontal and vertical coordinate ranges with [0, width - 1] and [0, height - 1] before touching the grid—keeps every index valid, while comparing against the original unclipped edges (x, x + w - 1, y, y + h - 1) preserves true border vs. interior cells.

Walk through Example 3's first rectangle (-1, -2, 4, 5, '#', ':') on a 5 x 4 grid: 1. The unclipped box spans columns -1..2 and rows -2..2; clipping against 0..4 and 0..3 leaves visible columns 0..2 and visible rows 0..2. 2. Rows 0 and 1 match neither y = -2 nor orig_bottom = 2, so columns 0..2 first receive ':' ("::: "), then x = -1 is off-grid while orig_right = 2 is visible and stamps '#' at column 2, producing "::# ". 3. Row 2 matches orig_bottom = 2, so columns 0..2 all receive '#', producing "### " before the second rectangle paints "#----" over row 2.

Complexity

Let A = width * height (at most 10^6), R be the number of rectangles, and a_i (across v_i visible rows) be the number of visible cells inside the canvas for rectangle i.

  • Time: O(A + R + sum(a_i)). Allocating the height x width space grid and joining the final strings each visit all A cells once; each of the R rectangles spends O(1) math to clip (immediately skipping completely off-screen shapes); and each visible rectangle writes its a_i visible characters using just v_i row-slice assignments in Python.
  • Space: O(A) to hold the height x width character grid and the height output strings of length width.

Edge cases

  • Zero width or zero height: height == 0 returns []; width == 0 returns height empty strings "". Because width - 1 or height - 1 is -1, col_start > col_end or row_start > row_end triggers immediately and skips all drawing.
  • Completely off-canvas rectangles: shapes wholly left of (orig_right < 0), right of (x >= width), above (orig_bottom < 0), or below (y >= height) the canvas yield an empty clipped range and return in O(1).
  • Negative x or y: clamping with max(x, 0) and max(y, 0) prevents Python negative-index wraparound.
  • Clipped corners and edges: cells sitting on col_start, col_end, row_start, or row_end remain fill_char unless that coordinate also equals x, orig_right, y, or orig_bottom.
  • One-cell-thin rectangles (w == 1 or h == 1): h == 1 has y == orig_bottom and w == 1 has x == orig_right, so every visible cell is painted with border_char and fill_char never appears.
  • Trailing spaces: joining all width cells of every row preserves blank columns on the right.

Common mistakes

  • Checking borders against clipped bounds: testing r == row_start or c == col_end instead of r == y or c == orig_right paints a fake border along the edge of the canvas whenever a rectangle sticks out.
  • Off-by-one on rectangle width/height: a rectangle at x of width w ends at x + w - 1, not x + w; using x + w makes every rectangle one column too wide.
  • Swapping (x, y) and (row, col): in screen coordinates, x indexes the column (0 .. width - 1) and y indexes the row (0 .. height - 1).
  • Row aliasing via [[" "] * width] * height: multiplying the outer list copies the same row reference height times, so drawing on row 0 mutates every row simultaneously.
  • Trimming spaces with .rstrip(): problem rules require every returned string to have exact length width.

Alternative approaches

  • Nested cell-by-cell loop over the clipped box: iterate for r in range(row_start, row_end + 1) and for c in range(col_start, col_end + 1) and check r in (y, orig_bottom) or c in (x, orig_right). Same O(A + R + sum(a_i)) asymptotic runtime, just slower in Python than whole-row slice assignment.
  • Reverse-order painting (topmost-first): iterate rectangles from last to first and write each canvas cell at most once, skipping cells already finalized (detailed in the third follow-up below).

Follow-up questions

  • If the grid dimensions were huge (for instance, 10^9 by 10^9) and almost empty, how would you return only the non-blank regions? Avoid allocating width * height cells altogether. Instead, represent each painted row as a sorted list of run-length intervals (compact (col_start, col_end, char) segments representing consecutive identical characters) stored in a dictionary keyed by row index r. Each visible row of a new rectangle contributes at most three intervals (left border, fill span, right border) that split and overwrite any overlapping intervals already in rows[r], keeping memory proportional to painted segments rather than total grid area.
  • How would you extend the specification to support transparent interiors or explicit layer priorities (z-order)? For transparent fills (for example fill_char is None), skip the interior slice write on non-border rows and only stamp row_cells[x] and row_cells[orig_right] when visible, allowing earlier rectangles to show through. For z-order (integer layer priorities where higher numbers sit closer to the viewer), sort the rectangles by z before drawing; because Python's sort is stable, rectangles with equal z retain their original input order so later ones still win ties.
  • Suppose 100,000 large rectangles all cover nearly the entire 1,000 by 1,000 grid—how could you avoid repainting the same cells repeatedly? Forward painting would overwrite the same million cells up to 10^5 times (10^11 writes). Instead, process rectangles in reverse input order so the first character written to any cell is final, and maintain per row a disjoint-set (union-find) array (a helper array of parent pointers with path compression that lets us jump straight to the next unpainted column >= c). Each of the A grid cells is painted and linked to c + 1 at most once across the entire run, bounding total cell writes to A.
  • Which targeted unit tests would you include to verify boundary clipping, 1-unit dimensions, and overlap ordering? Test each boundary rule independently with hand-computed outputs: (1) complete off-grid clipping on all four sides (x + w - 1 == -1, x == width, y + h - 1 == -1, y == height), (2) corner clipping where the cut-off corner cell inside the grid must stay fill_char, (3) 1 x h, w x 1, and 1 x 1 thin shapes, (4) two overlapping rectangles rendered in both [A, B] and [B, A] orders, (5) width == 0 and height == 0 grids, and (6) a randomized property check comparing against a naive cell-by-cell loop.

Follow-up questions

Similar questions

More Amperity interview questions

All 6 Amperity questions →