Magicsheet logo

Stamping the Grid

Hard
67.8%
Updated 6/1/2025

Asked by 1 Company

Stamping the Grid

What is this problem about?

The Stamping the Grid coding problem is a "Hard" difficulty matrix challenge. You are given a grid of 0s (empty) and 1s (occupied), along with a stamp of size h×wh \times w. You can place the stamp on any h×wh \times w area of the grid that contains only 0s. The goal is to determine if it's possible to cover all the 0s in the grid using any number of stamps. Stamps can overlap, but they cannot cover any 1s.

Why is this asked in interviews?

Asked by Rubrik, this problem tests a candidate's mastery of 2D data structures and Greedy interview pattern. It's a complex multi-step problem: first, you need to find all valid stamp positions, and second, you need to check if those stamps cover everything. It requires efficient range-sum or range-update techniques to avoid O(N2×M2)O(N^2 \times M^2) complexity.

Algorithmic pattern used

The algorithm uses a Greedy approach with 2D Prefix Sums (or 2D Difference Arrays).

  1. Use 2D Prefix Sums to quickly check if any h×wh \times w area contains a 1. If not, it's a valid stamp position.
  2. Mark all cells covered by these valid stamps. This is efficiently done using a 2D Difference Array (also known as a 2D partial sum array).
  3. After processing all possible stamp positions, calculate the actual coverage using the difference array and check if any 0 in the original grid remains uncovered.

Example explanation (use your own example)

Imagine a 5x5 grid with a 1 at the center (2,2) and a stamp size 2x2.

  • Any 2x2 area that includes (2,2) is invalid.
  • We check all other 2x2 areas. For example, (0,0) to (1,1) is valid.
  • We place stamps on all valid 2x2 areas.
  • Finally, we check if any 0-cell was never touched by a stamp. If the 1 at (2,2) prevents the stamp from reaching a 0-cell at (2,1) or (1,2) effectively, then it's impossible.

Common mistakes candidates make

  • Slow checking: Iterating through every cell of a stamp area to check for 1s instead of using 2D Prefix Sums.
  • Slow marking: Iterating through every cell of a stamp area to mark it as covered instead of using a 2D Difference Array.
  • Boundary issues: Missing valid stamp positions near the edges of the grid.
  • Misunderstanding the constraint: Forgetting that stamps cannot be placed if they overlap even a single 1.

Interview preparation tip

Mastering 2D Prefix Sums is essential for Matrix interview pattern problems involving subgrids. It allows you to query the sum of any rectangle in O(1)O(1) time after O(NM)O(NM) pre-processing.

Similar Questions