Stamping the Grid - Problem

You are given an m x n binary matrix grid where each cell is either 0 (empty) or 1 (occupied).

You are then given stamps of size stampHeight x stampWidth. We want to fit the stamps such that they follow the given restrictions and requirements:

  • Cover all the empty cells.
  • Do not cover any of the occupied cells.
  • We can put as many stamps as we want.
  • Stamps can overlap with each other.
  • Stamps are not allowed to be rotated.
  • Stamps must stay completely inside the grid.

Return true if it is possible to fit the stamps while following the given restrictions and requirements. Otherwise, return false.

Input & Output

Example 1 — Basic Case
$ Input: grid = [[1,0,0,0],[1,0,0,0],[1,0,0,0]], stampHeight = 1, stampWidth = 3
Output: true
💡 Note: We can place 1×3 stamps at positions (0,1), (1,1), and (2,1) to cover all empty cells without covering any occupied cells
Example 2 — Impossible Case
$ Input: grid = [[1,0,0,0],[0,1,0,0],[0,0,1,0]], stampHeight = 2, stampWidth = 2
Output: false
💡 Note: No 2×2 stamp can be placed without covering at least one occupied cell (1), so it's impossible to cover all empty cells
Example 3 — Small Stamp
$ Input: grid = [[1,0,0],[1,0,0],[1,0,0]], stampHeight = 1, stampWidth = 1
Output: true
💡 Note: 1×1 stamps can be placed at all empty positions (0,1), (0,2), (1,1), (1,2), (2,1), (2,2) to cover everything

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

Visualization

Tap to expand
Stamping the Grid INPUT Binary Grid (3x4) 1 0 0 0 1 0 0 0 1 0 0 0 Occupied (1) Empty (0) Stamp Size Height: 1, Width: 3 1x3 Stamp ALGORITHM STEPS 1 Prefix Sum Matrix Build 2D prefix sum for quick region queries 2 Find Valid Positions Check where stamps fit (all cells must be 0) 3 Difference Array Mark stamp coverage using 2D diff array 4 Verify Coverage Check all empty cells are covered by stamps Valid Stamp Positions: Overlapping stamps OK FINAL RESULT All Empty Cells Covered 1 1 1 Stamped Occupied Output: true All 9 empty cells covered by 1x3 stamps - OK Key Insight: Use 2D prefix sums to quickly check if a stamp region contains only empty cells (sum = 0). Apply 2D difference array to efficiently mark all cells covered by stamps in O(1) per stamp. Time Complexity: O(m*n) | Space Complexity: O(m*n) for prefix and difference arrays. TutorialsPoint - Stamping the Grid | Optimal Solution (Prefix Sum + Difference Array)
Asked in
Google 15 Meta 12
23.0K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen