Place Pieces on a Grid
Capital OneSoftware Engineer · OnsiteLast updated
This question evaluates spatial reasoning, matrix and array manipulation, collision detection, and stateful simulation skills required to implement ordered placement of shaped pieces on a grid.
Given integers n and m, and an ordered list figures where each element is one of "A", "B", "C", "D", or "E", construct an n x m integer matrix grid.
The grid starts with all values equal to 0.
Each figure has a fixed shape described by a binary matrix, where 1 means the figure occupies that cell and 0 means empty space:
A = [[1]]B = [[1, 1, 1]]C = [[1, 1], [1, 1]]D = [[1, 0], [1, 1], [1, 0]]E = [[0, 1, 0], [1, 1, 1]]
Process the figures in the given order. For the figure at index i:
- Try all possible top-left placement positions in row-major order:
(0, 0),(0, 1), ...,(0, m - 1),(1, 0), ... . - A placement is valid if every
1cell of the figure:
- stays within the bounds of the grid, and
- overlaps only cells that are currently
0.
- Place the figure at the first valid position.
- Fill every occupied cell of that placed figure with the value
i + 1. - If the figure cannot be placed anywhere, skip it and leave the grid unchanged.
Return the final grid.
Figures cannot be rotated or reflected.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.