Stamping the Grid - Problem
Stamping the Grid is a challenging matrix problem that simulates placing rectangular stamps on a grid. You are given an
Your task is to determine if you can place rectangular stamps of size
β Must cover all empty cells (0s)
β Cannot cover any occupied cells (1s)
π Stamps can overlap with each other
π Stamps cannot be rotated
π¦ Stamps must stay completely inside the grid
Return
m Γ n binary matrix where 0 represents empty cells and 1 represents occupied cells.Your task is to determine if you can place rectangular stamps of size
stampHeight Γ stampWidth to cover all empty cells while following these rules:β Must cover all empty cells (0s)
β Cannot cover any occupied cells (1s)
π Stamps can overlap with each other
π Stamps cannot be rotated
π¦ Stamps must stay completely inside the grid
Return
true if it's possible to stamp all empty cells, false otherwise. Input & Output
example_1.py β Basic Grid
$
Input:
grid = [[1,0,0,0],[1,0,0,0],[1,0,0,0],[1,0,0,0],[1,0,0,0]], stampHeight = 4, stampWidth = 3
βΊ
Output:
true
π‘ Note:
We can place one 4Γ3 stamp starting at position (0,1) to cover all the empty cells in columns 1-3. The stamp doesn't overlap with any occupied cells (the 1s in column 0).
example_2.py β Impossible Case
$
Input:
grid = [[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]], stampHeight = 2, stampWidth = 2
βΊ
Output:
false
π‘ Note:
No 2Γ2 stamp can be placed without covering at least one occupied cell (1). The diagonal pattern of obstacles makes it impossible to place any stamp.
example_3.py β Multiple Stamps Needed
$
Input:
grid = [[1,0,0,1],[0,0,0,0],[0,0,0,0],[1,0,0,1]], stampHeight = 2, stampWidth = 2
βΊ
Output:
true
π‘ Note:
We can place a 2Γ2 stamp at position (1,1) to cover the 2Γ2 area of empty cells in the middle. This covers all empty cells without touching the occupied corners.
Visualization
Tap to expand
Understanding the Visualization
1
Identify Obstacles
Mark all occupied cells (furniture) that cannot be covered
2
Find Valid Tile Positions
Determine all positions where a tile can be placed without hitting obstacles
3
Check Coverage
Verify that every empty floor space can be covered by at least one valid tile placement
Key Takeaway
π― Key Insight: Use 2D prefix sums to transform expensive O(stampHeightΓstampWidth) range checks into O(1) operations, making the overall algorithm run in optimal O(mΓn) time.
Time & Space Complexity
Time Complexity
O(m*n)
Single pass through grid with O(1) range queries using prefix sums
β Linear Growth
Space Complexity
O(m*n)
Additional space for prefix sum arrays and coverage matrix
β‘ Linearithmic Space
Constraints
- m == grid.length
- n == grid[r].length
- 1 β€ m, n β€ 105
- 1 β€ m * n β€ 2 * 105
- grid[r][c] is either 0 or 1
- 1 β€ stampHeight, stampWidth β€ 105
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code