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 columnxand rowy.wandhgive the horizontal width (spanning columnsxthroughx + w - 1) and vertical height (spanning rowsythroughy + h - 1).- Any cell lying on the outer perimeter of the full unclipped rectangle (
col == x,col == x + w - 1,row == y, orrow == y + h - 1) is drawn withborder_char. - Any cell strictly inside that perimeter is drawn with
fill_char. Whenw == 1orh == 1, the rectangle has no interior cells, so every cell of the shape usesborder_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 <= 1000width * height <= 10^61 <= w, h <= 1000xandyare integers and may be negative, zero, or larger than the grid dimensions.border_charandfill_charare single printable ASCII characters.
Step-by-step walkthrough
Understand coordinates, borders, and overlaps
We start with a blank ASCII canvas of
widthcolumns (0 .. width - 1) andheightrows (0 .. height - 1), initially filled with space characters' '. Each rectangle(x, y, w, h, border_char, fill_char)has its upper-left corner at columnx, rowy, spanswcolumns (x .. x + w - 1) andhrows (y .. y + h - 1), usesborder_charon its outermost ring, and usesfill_charstrictly 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:
xorycan be negative, andx + wory + hcan exceed the canvas size; only the part landing inside the canvas is drawn. - Exact row width: the output has
heightstrings of lengthwidth, keeping all trailing spaces.
Brute force and where it struggles
The simplest mental model visits every cell
(r, c)of the fullw x hrectangle, checks whether(r, c)lies inside the canvas, and writesborder_charorfill_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_charThis produces the right answer, and
tests.pyuses it as a randomized oracle. However, it loops over cells that sit completely off-canvas, and on a1,000 x 1,000canvas (10^6cells) running millions of inner-loop Python iterations per rectangle adds heavy interpreter overhead.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 a4 x 4canvas: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
3and row3are the last visible positions on the4 x 4canvas (col_end = 3,row_end = 3), the rectangle's real right and bottom borders sit out at column6and row6. 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.
- Clipped bounds (
Code the rectangle clipping
Let's start
draw_rectangleby computing the original inclusive end coordinates and intersecting them with the canvas. Notice two safety wins we get immediately:- Clamping with
max(x, 0)andmax(y, 0)blocks negative numbers, which in Python would otherwise wrap around (row[-1]silently mutates the last column!). - Checking
col_start > col_end or row_start > row_endcatches both off-screen rectangles and degenerate canvases (width == 0orheight == 0, wherewidth - 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- Clamping with
Paint each visible row with slice assignment
For each visible row
rfromrow_starttorow_end, every cell incol_start .. col_endfollows one of two simple patterns:- Top or bottom border row (
r == yorr == orig_bottom): the entire visible horizontal span isborder_char. - Interior row: write
fill_characross the entire visible span in a single slice assignment, then overwriterow_cells[x]if the original left borderxlies inside[col_start, col_end], and overwriterow_cells[orig_right]if the original right borderorig_rightlies inside[col_start, col_end].
Thin rectangles work without any special case:
h == 1hasy == orig_bottom(hit by the first branch), andw == 1hasx == orig_right(so the stamp overwrites the single cell withborder_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- Top or bottom border row (
Initialize the canvas, draw in order, and trace Example 3
Because Python
strobjects are immutable, we represent the canvas asheightseparate lists ofwidthspaces ([" "] * widthinside 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_rowsLet'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: " "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 theheight x widthspace grid and joining the final strings each visit allAcells once; each of theRrectangles spendsO(1)math to clip (immediately skipping completely off-screen shapes); and each visible rectangle writes itsa_ivisible characters using justv_irow-slice assignments in Python. - Space:
O(A)to hold theheight x widthcharacter grid and theheightoutput strings of lengthwidth.
Edge cases
- Zero width or zero height:
height == 0returns[];width == 0returnsheightempty strings"". Becausewidth - 1orheight - 1is-1,col_start > col_endorrow_start > row_endtriggers 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 inO(1). - Negative
xory: clamping withmax(x, 0)andmax(y, 0)prevents Python negative-index wraparound. - Clipped corners and edges: cells sitting on
col_start,col_end,row_start, orrow_endremainfill_charunless that coordinate also equalsx,orig_right,y, ororig_bottom. - One-cell-thin rectangles (
w == 1orh == 1):h == 1hasy == orig_bottomandw == 1hasx == orig_right, so every visible cell is painted withborder_charandfill_charnever appears. - Trailing spaces: joining all
widthcells of every row preserves blank columns on the right.
Common mistakes
- Checking borders against clipped bounds: testing
r == row_startorc == col_endinstead ofr == yorc == orig_rightpaints a fake border along the edge of the canvas whenever a rectangle sticks out. - Off-by-one on rectangle width/height: a rectangle at
xof widthwends atx + w - 1, notx + w; usingx + wmakes every rectangle one column too wide. - Swapping
(x, y)and(row, col): in screen coordinates,xindexes the column (0 .. width - 1) andyindexes the row (0 .. height - 1). - Row aliasing via
[[" "] * width] * height: multiplying the outer list copies the same row referenceheighttimes, so drawing on row0mutates every row simultaneously. - Trimming spaces with
.rstrip(): problem rules require every returned string to have exact lengthwidth.
Alternative approaches
- Nested cell-by-cell loop over the clipped box: iterate
for r in range(row_start, row_end + 1)andfor c in range(col_start, col_end + 1)and checkr in (y, orig_bottom) or c in (x, orig_right). SameO(A + R + sum(a_i))asymptotic runtime, just slower in Python than whole-row slice assignment. - Reverse-order painting (topmost-first): iterate
rectanglesfrom 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 * heightcells 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 indexr. 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 inrows[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 stamprow_cells[x]androw_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 byzbefore drawing; because Python'ssortis stable, rectangles with equalzretain 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^5times (10^11writes). 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 theAgrid cells is painted and linked toc + 1at most once across the entire run, bounding total cell writes toA. - 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 stayfill_char, (3)1 x h,w x 1, and1 x 1thin shapes, (4) two overlapping rectangles rendered in both[A, B]and[B, A]orders, (5)width == 0andheight == 0grids, and (6) a randomized property check comparing against a naive cell-by-cell loop.
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?
- How would you extend the specification to support transparent interiors or explicit layer priorities (z-order)?
- 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?
- Which targeted unit tests would you include to verify boundary clipping, 1-unit dimensions, and overlap ordering?
Similar questions
- Winning Business Buy-In for Technical Initiatives
- Distributed Time-Series Telemetry and Query Platform
- Architecting a Multi-Tenant Cloud SQL Platform on Apache Iceberg
- Headless Minesweeper Game Engine
- Navigating a High-Stakes Engineering Roadblock
- 2D Max Pooling with Source Coordinates