FastPrepLayered Rectangle Canvas

Layered Rectangle Canvas

Rippling logoRippling● MediumFULLTIMEONSITE INTERVIEW
Learn

Problem statement

You are given a rectangular character canvas with rows rows and cols columns. Every uncovered cell initially contains '.'.

Process each string in commands from left to right. Coordinates are zero-indexed, and every command has one of these forms:

  • DRAW id top left height width ch creates a filled rectangle with a unique identifier id. Its top-left cell is (top, left), it occupies height rows and width columns, and every occupied cell contributes the uppercase character ch. A newly drawn rectangle is placed above every rectangle that already exists.
  • MOVE id rowDelta colDelta translates the existing rectangle id by adding rowDelta to its top coordinate and colDelta to its left coordinate. Moving a rectangle does not change its layer position.

At any cell covered by multiple rectangles, the topmost rectangle contributes the visible character. When a rectangle moves away, any lower rectangle underneath it becomes visible again.

Return the final canvas as an array of rows strings, each of length cols.

Function

renderRectangleCanvas(rows: int, cols: int, commands: String[]) → String[]

Examples

Example 1

rows = 4cols = 7commands = ["DRAW back 0 0 3 4 A","DRAW front 1 2 2 4 B"]return = ["AAAA...","AABBBB.","AABBBB.","......."]

The rectangle front was drawn later, so its 'B' cells cover the overlapping portion of back.

Example 2

rows = 4cols = 6commands = ["DRAW low 0 0 2 3 L","DRAW high 1 1 2 3 H","MOVE low 1 2"]return = ["......",".HHHL.",".HHHL.","......"]

Moving low preserves its original lower layer. Its cells become visible only where high does not cover them.

Example 3

rows = 5cols = 7commands = ["DRAW base 1 1 3 5 X","DRAW top 2 2 2 2 O","MOVE top -1 3"]return = [".......",".XXXXOO",".XXXXOO",".XXXXX.","......."]

The upper rectangle moves to columns 5 and 6. Its old cells reveal base, while its new overlap at column 5 remains visible as 'O'.

Constraints

  • 1 <= rows, cols <= 50.
  • 1 <= commands.length <= 1000.
  • At most 200 rectangles are drawn.
  • Every id is a nonempty alphanumeric string; each DRAW uses a new ID, and each MOVE names an existing ID.
  • Each ch is one uppercase English letter.
  • Every rectangle has positive height and width, and every draw or move leaves the complete rectangle inside the canvas.

More Rippling problems

See Rippling hiring insights
public String[] renderRectangleCanvas(int rows, int cols, String[] commands) {
    // Write your code here.
}
rows4
cols7
commands["DRAW back 0 0 3 4 A","DRAW front 1 2 2 4 B"]
expected["AAAA...", "AABBBB.", "AABBBB.", "......."]
Checking account…