Sequential Shape Placement on a Matrix
Arrays & HashingAuto-graded · 21 test casesLast updated
Tests matrix manipulation, collision detection, and ordered simulation by placing fixed shapes onto a grid.
You are given two positive integers n and m representing the dimensions of a grid, and a list figures containing shape identifiers. Each identifier is one of "A", "B", "C", "D", or "E".
Your task is to build an n × m matrix that starts filled with zeros. You will then place each shape from figures onto this matrix in the order given.
Each shape is defined by a pattern where 1 indicates an occupied cell and 0 indicates an empty cell:
- Shape
A:[[1]](a single cell) - Shape
B:[[1, 1, 1]](a horizontal bar of length 3) - Shape
C:[[1, 1], [1, 1]](a 2×2 square) - Shape
D:[[1, 0], [1, 1], [1, 0]](a vertical T-shape) - Shape
E:[[0, 1, 0], [1, 1, 1]](an inverted T-shape)
For each shape in sequence (using zero-based indexing i):
- Scan all possible positions in the grid from top to bottom, left to right (position
(r, c)represents where the shape's top-left corner would be placed). - A position is valid only if:
- Every cell marked
1in the shape stays within the grid boundaries. - Every cell marked
1in the shape overlaps only grid cells that currently contain0.
- Every cell marked
- Place the shape at the first valid position found. Mark each cell occupied by a
1in the shape with the valuei + 1. - If no valid position exists for a shape, skip it entirely (the grid remains unchanged for that shape).
Shapes cannot be rotated or flipped. Cells marked 0 in a shape pattern are ignored and do not affect placement.
Return the final matrix after processing all shapes.
Constraints
1 ≤ n, m ≤ 1000 ≤ len(figures) ≤ 1000- Each element in
figuresis one of"A","B","C","D","E"
Examples
Example 1
Input: sequential_shape_placement(4, 5, ['A', 'B', 'C', 'D', 'E'])
Output: [[1, 2, 2, 2, 0], [3, 3, 4, 0, 0], [3, 3, 4, 4, 0], [0, 0, 4, 0, 0]]
Example 2
Input: sequential_shape_placement(2, 3, ['E', 'A', 'B'])
Output: [[2, 1, 0], [1, 1, 1]]
Example 3
Input: sequential_shape_placement(3, 4, ['D', 'D', 'D'])
Output: [[1, 0, 2, 0], [1, 1, 2, 2], [1, 0, 2, 0]]
Hints
Hint 1
Scan positions in row-major order: iterate rows first, then columns within each row.
Hint 2
A shape can be placed even if its empty cells (marked 0) overlap filled grid cells—only the occupied cells (marked 1) matter.
Hint 3
Each shape receives a label equal to its index plus one, regardless of whether earlier shapes were skipped.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem requires simulating the placement process exactly as specified. The solution has three main components:
-
Store shape definitions in a dictionary mapping each identifier to its binary pattern matrix.
-
For each shape in order, attempt to place it by scanning all possible top-left anchor positions in row-major order (top to bottom, left to right).
-
Validate each position by checking:
- The shape's bounding box fits within the grid boundaries
- Every occupied cell (
1in the pattern) would land on an empty grid cell (0)
Note that cells marked
0in the shape pattern don't participate in the validation—only the1cells matter. -
Place at the first valid position by writing
idx + 1to each occupied cell, then move to the next shape. If no valid position exists, skip the shape without modifying the grid.
The key insight is that this is a straightforward simulation with no optimization needed. The first valid position in scan order is always chosen, making this a greedy algorithm by specification.
Why It Works
The nested loop structure with the outer loop over rows and inner loop over columns produces row-major order naturally. Using a placed flag and breaking from both loops ensures each shape is placed at most once at its first valid position.
The boundary check r + rows > n or c + cols > m is sufficient because:
- All shapes have at least one
1in their bottom row and rightmost column - Anchors are never negative
- Therefore, if the bounding box extends past the grid's right or bottom edge, at least one occupied cell is also out of bounds
Complexity
- Time: O(F × n × m × k) where F is the number of shapes and k is the maximum cells in a shape pattern. Since k ≤ 6 for these shapes, this simplifies to O(F × n × m).
- Space: O(n × m) for the output grid. The shape dictionary is constant size.
Solution Code
from typing import List
def sequential_shape_placement(n: int, m: int, figures: List[str]) -> List[List[int]]:
shape_patterns = {
"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]],
}
grid = [[0] * m for _ in range(n)]
for idx, shape_id in enumerate(figures):
pattern = shape_patterns[shape_id]
rows, cols = len(pattern), len(pattern[0])
placed = False
for r in range(n):
if placed:
break
for c in range(m):
if r + rows > n or c + cols > m:
continue
can_place = all(
not pattern[dr][dc] or grid[r + dr][c + dc] == 0
for dr in range(rows)
for dc in range(cols)
)
if can_place:
for dr in range(rows):
for dc in range(cols):
if pattern[dr][dc]:
grid[r + dr][c + dc] = idx + 1
placed = True
break
return grid