#2132

Stamping the Grid

Hard
ArrayGreedyMatrixPrefix SumGreedyPrefix SumMatrix
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(m * n)
Space
O(1)
O(m * n)
💡

Intuition

Time O(m * n)Space O(m * n)

The optimal solution uses a greedy approach combined with prefix sums to efficiently determine if all empty cells can be covered by stamps. This method reduces the number of checks needed by leveraging cumulative sums.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a prefix sum array to track the number of empty cells in any submatrix of size stampHeight x stampWidth.
  2. 2Step 2: Iterate through the grid and for each empty cell, check if placing a stamp at that position would cover all empty cells in the stamp area.
  3. 3Step 3: If all empty cells can be covered, return true; otherwise, return false.
solution.py13 lines
1def canStamp(grid, stampHeight, stampWidth):
2    m, n = len(grid), len(grid[0])
3    prefix = [[0] * (n + 1) for _ in range(m + 1)]
4    
5    for i in range(m):
6        for j in range(n):
7            prefix[i + 1][j + 1] = grid[i][j] + prefix[i][j + 1] + prefix[i + 1][j] - prefix[i][j]
8    
9    for i in range(m - stampHeight + 1):
10        for j in range(n - stampWidth + 1):
11            if prefix[i + stampHeight][j + stampWidth] - prefix[i][j + stampWidth] - prefix[i + stampHeight][j] + prefix[i][j] == 0:
12                return True
13    return False

Complexity note: The time complexity is O(m * n) because we need to compute the prefix sums for the entire grid. The space complexity is also O(m * n) for storing the prefix sum array.

  • 1Using prefix sums can significantly reduce the number of checks needed.
  • 2Greedy approaches can often lead to optimal solutions when combined with cumulative data.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.