Square Submatrices Filled with Ones

Medium · Coding & Algorithms · Software Engineer · Technical Screen

Problem Statement

You are given a rectangular grid grid of m rows and n columns in which each cell holds either 0 or 1. Implement count_squares(grid: List[List[int]]) -> int to compute how many contiguous k x k square blocks (k >= 1) inside grid contain exclusively 1s.

A k x k block anchored at top-left cell (r, c) covers rows r through r + k - 1 and columns c through c + k - 1 (with r + k <= m and c + k <= n). Single-cell 1 x 1 blocks count whenever the cell holds 1, and overlapping blocks or blocks of different side lengths are all counted separately.

Examples

Example 1

Input:
grid = [
  [1, 1, 1, 0],
  [1, 1, 1, 1],
  [0, 1, 1, 1],
  [0, 1, 1, 1]
]

Output: 20

Walk-through: - 1 x 1 blocks: 13 (every cell equal to 1). - 2 x 2 blocks: 6 (top-left corners at (0, 0), (0, 1), (1, 1), (1, 2), (2, 1), and (2, 2)). - 3 x 3 blocks: 1 (covering rows 1..3 and columns 1..3). - Adding all sizes together gives 13 + 6 + 1 = 20.

Example 2

Input:
grid = [
  [1, 1, 0, 1],
  [1, 1, 1, 1]
]

Output: 8

Walk-through: - 1 x 1 blocks: 7 cells contain 1. - 2 x 2 blocks: 1 block spans columns 0..1; the 0 at (0, 2) prevents any 2 x 2 block from using columns 1..2 or 2..3. - Total count: 7 + 1 = 8.

Constraints

  • 1 <= len(grid) <= 300
  • 1 <= len(grid[0]) <= 300 (all rows have the same length)
  • Every entry grid[r][c] is either 0 or 1.

Step-by-step walkthrough

  1. Understand the goal

    We receive an m x n grid of 0s and 1s (1 <= m, n <= 300) and want the total count of square blocks filled exclusively with 1s.

    Squares of every side length (1 x 1, 2 x 2, 3 x 3, ...) count separately, and squares may overlap:

    Example 1 grid:
      1  1  1  0      - Thirteen 1 x 1 squares (every cell holding a 1)
      1  1  1  1      - Six      2 x 2 squares
      0  1  1  1      - One      3 x 3 square  (rows 1..3, cols 1..3)
      0  1  1  1      Total = 13 + 6 + 1 = 20
    
  2. Why checking every square from scratch is too slow

    A square is uniquely specified by its top-left corner (r, c) and its side length k. What happens if we test every (r, c) and every k by scanning all k * k cells inside?

    • On a 300 x 300 grid, there are 300 * 300 = 90,000 top-left corners.
    • Each corner can try up to 300 side lengths k.
    • Verifying one k x k square reads up to k^2 cells (90,000 cells when k = 300).

    Summing k^2 * (301 - k)^2 across k = 1..300 comes to roughly 82 billion cell reads (O(m * n * min(m, n)^3)). Even if we grow each square one ring at a time and check only the 2k - 1 newly added border cells, an all-1s 300 x 300 grid still takes about 1.35 billion cell reads (O(m * n * min(m, n)^2)). We are doing wasted work because overlapping squares keep re-checking the exact same 1s!

  3. Key insight: Group squares by their bottom-right corner

    Instead of starting at top-left corners and growing outward, anchor every valid square by its bottom-right corner (r, c). Define:

    side[r][c] = side length k of the largest all-1s square whose bottom-right corner is (r, c) (0 if grid[r][c] == 0).

    Look at what happens when side[r][c] == 3 at (3, 3) in Example 1:

      .  1  1  1       3 x 3 square ends at (3, 3)  (rows 1..3, cols 1..3)
      .  1 [1  1]      2 x 2 square ends at (3, 3)  (nested inside the 3 x 3)
      .  1 [1 (1)]     1 x 1 square ends at (3, 3)  (nested inside the 2 x 2)
    

    Whenever the largest all-1s square ending at (r, c) has side k, the smaller squares of side 1, 2, ..., k - 1 ending at (r, c) sit completely inside it — so all k of them are guaranteed to be all 1s, and no (k + 1) x (k + 1) square ending at (r, c) is valid! Because every square in the grid has one unique bottom-right corner, the total number of all-1s squares is simply the sum of side[r][c] over every cell (r, c).

  4. Why the minimum of three neighbors gives `side[r][c]`

    How do we compute side[r][c] in O(1) time without scanning backward?

    • If grid[r][c] == 0, no all-1s square can end at (r, c), so side[r][c] = 0.
    • If grid[r][c] == 1 and r == 0 or c == 0 (top row or left column), there is no room above or to the left for a 2 x 2 square, so side[r][c] = 1.
    • Otherwise (grid[r][c] == 1, r > 0, c > 0), look at the three neighbor cells up = (r - 1, c), left = (r, c - 1), and up_left = (r - 1, c - 1):
    A k x k square ending at (r, c) (shown here for k = 3):
    
      +-------+---+     - Top-left (k-1)x(k-1) square ends at (r-1, c-1) [up_left]
      |       |   |     - Top      (k-1)x(k-1) square ends at (r-1, c)   [up]
      +---+   |   |     - Left     (k-1)x(k-1) square ends at (r,   c-1) [left]
      |   |   |   |     - Plus the corner cell (r, c) itself = 1
      +---+---+---+
      |   |   |1  | <-- (r, c)
      +---+---+---+
    

    Those three (k - 1) x (k - 1) neighbor squares plus (r, c) cover every single cell of the k x k square! Therefore:

    • If all three neighbors have side >= k - 1, every cell in the k x k square is 1.
    • If any of the three neighbors has side < k - 1, there is a 0 (or grid boundary) inside that region that also blocks the k x k square.

    So the largest valid side ending at (r, c) is constrained by the weakest of the three neighbors:

    side[r][c] = 1 + min(side[r - 1][c], side[r][c - 1], side[r - 1][c - 1])

  5. Write the dynamic programming loop

    Because (r, c) only reads (r - 1, c), (r, c - 1), and (r - 1, c - 1), iterating row by row (r = 0 .. rows - 1) and left to right (c = 0 .. cols - 1) guarantees all three neighbor values are already computed when we reach (r, c).

        rows = len(grid)
        cols = len(grid[0])
    
        # side[r][c]: side length k of the largest all-1s square whose bottom-right
        # corner is (r, c), e.g. side[r][c] == 3 means 1x1, 2x2, and 3x3 all end here.
        side: List[List[int]] = [[0] * cols for _ in range(rows)]
        total_squares = 0
    
        # Fill row by row, left to right, so top, left, and top-left neighbors are ready.
        for r in range(rows):
            for c in range(cols):
                # No all-1s square can have a 0 at its bottom-right corner.
                if grid[r][c] == 0:
                    continue
    
                # Cells on the top edge or left edge can only end a 1x1 square.
                if r == 0 or c == 0:
                    side[r][c] = 1
                else:
                    up = side[r - 1][c]
                    left = side[r][c - 1]
                    up_left = side[r - 1][c - 1]
                    # A k x k square ending at (r, c) exists iff all three overlapping
                    # (k - 1) x (k - 1) neighbor squares also exist; weakest neighbor caps k.
                    side[r][c] = 1 + min(up, left, up_left)
    
                # Largest side k means squares of side 1, 2, ..., k all end at (r, c).
                total_squares += side[r][c]
    
        return total_squares
    
  6. Trace through Example 1 cell by cell

    Let's fill side for Example 1 and add each row's contributions:

    Input grid:             Computed side[r][c]:        Row sums:
      1  1  1  0              1  1  1  0                1 + 1 + 1 + 0 =  3
      1  1  1  1    --->      1  2  2  1                1 + 2 + 2 + 1 =  6
      0  1  1  1              0  1  2  2                0 + 1 + 2 + 2 =  5
      0  1  1  1              0  1  2  3                0 + 1 + 2 + 3 =  6
                                                        ------------------
                                                        total_squares = 20
    

    Checking the key interior cells:

    • (1, 3): up = 0 (from (0, 3)), left = 2, up_left = 1 -> 1 + min(0, 2, 1) = 1.
    • (2, 1): up = 2, left = 0 (from (2, 0)), up_left = 1 -> 1 + min(2, 0, 1) = 1.
    • (2, 2): up = 2, left = 1, up_left = 2 -> 1 + min(2, 1, 2) = 2 (1 x 1 and 2 x 2 end here).
    • (3, 3): up = 2, left = 2, up_left = 2 -> 1 + min(2, 2, 2) = 3 (1 x 1, 2 x 2, and 3 x 3 all end here!).
  7. Complete solution

    from typing import Any, Dict, List, Optional, Set, Tuple
    
    
    def count_squares(grid: List[List[int]]) -> int:
        if not grid or not grid[0]:
            return 0
    
        rows = len(grid)
        cols = len(grid[0])
    
        # side[r][c]: side length k of the largest all-1s square whose bottom-right
        # corner is (r, c), e.g. side[r][c] == 3 means 1x1, 2x2, and 3x3 all end here.
        side: List[List[int]] = [[0] * cols for _ in range(rows)]
        total_squares = 0
    
        # Fill row by row, left to right, so top, left, and top-left neighbors are ready.
        for r in range(rows):
            for c in range(cols):
                # No all-1s square can have a 0 at its bottom-right corner.
                if grid[r][c] == 0:
                    continue
    
                # Cells on the top edge or left edge can only end a 1x1 square.
                if r == 0 or c == 0:
                    side[r][c] = 1
                else:
                    up = side[r - 1][c]
                    left = side[r][c - 1]
                    up_left = side[r - 1][c - 1]
                    # A k x k square ending at (r, c) exists iff all three overlapping
                    # (k - 1) x (k - 1) neighbor squares also exist; weakest neighbor caps k.
                    side[r][c] = 1 + min(up, left, up_left)
    
                # Largest side k means squares of side 1, 2, ..., k all end at (r, c).
                total_squares += side[r][c]
    
        return total_squares
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine laying square carpet tiles (1 x 1, 2 x 2, 3 x 3, ...) onto a room floor where 0s mark pillars you cannot cover, and tagging every valid carpet square by its bottom-right corner (r, c). If the largest pillar-free square ending at (r, c) has side length 3, then the 2 x 2 square and 1 x 1 square ending at that exact same corner sit tucked inside it automatically — meaning (r, c) contributes 3 valid squares at once!

Testing every top-left corner, every side length k, and every cell inside each k x k square re-reads the same interior 1s thousands of times, taking roughly 82 billion cell checks on a 300 x 300 grid. Instead, we use dynamic programming (solving complex problems by storing answers to smaller overlapping subproblems in a table so each subproblem is computed only once). We store side[r][c] = the largest all-1s square ending at (r, c): when grid[r][c] == 1, side[r][c] = 1 + min(side[r - 1][c], side[r][c - 1], side[r - 1][c - 1]) because those three (k - 1) x (k - 1) neighbor squares plus (r, c) cover the entire k x k square, and summing side[r][c] across all cells counts every valid square once.

Walk through a tiny 2 x 2 grid [[0, 1], [1, 1]]:

  1. (0, 0) has value 0 -> side[0][0] = 0 (total = 0).
  2. (0, 1) has value 1 on row 0 -> side[0][1] = 1 (total = 1).
  3. (1, 0) has value 1 on column 0 -> side[1][0] = 1 (total = 2).
  4. (1, 1) has value 1, with up = 1, left = 1, up_left = 0 -> side[1][1] = 1 + min(1, 1, 0) = 1 (the 0 at (0, 0) blocks a 2 x 2 square!), giving total = 2 + 1 = 3.

Complexity

  • Time: O(m * n), where m is the number of rows and n is the number of columns. We visit each of the m * n cells once and perform a constant O(1) amount of work per cell (one zero check, at most three array reads, min of three ints, and one addition).
  • Space: O(m * n) for the side table of m rows by n columns, keeping the caller's input grid unmodified. Because row r only reads row r - 1, auxiliary space can be reduced to O(n) using two 1D rows (see Follow-up 1).

Edge cases

  • 1 x 1 matrix: [[1]] hits r == 0 and returns 1; [[0]] skips at grid[r][c] == 0 and returns 0.
  • All 0s: every entry in side stays 0, returning 0.
  • All 1s (m x n): every size k from 1 to min(m, n) contributes (m - k + 1) * (n - k + 1) squares; for 300 x 300, 1^2 + 2^2 + ... + 300^2 = 9,045,050, which easily fits in standard 32-bit and Python integers.
  • Single row (1 x n) or single column (m x 1): every cell satisfies r == 0 or c == 0, so only 1 x 1 squares count and the total equals the count of 1s.
  • Single 0 inside a sea of 1s: its side of 0 caps min(up, left, up_left) for its right, bottom, and bottom-right neighbors, preventing any larger square from covering the 0.

Common mistakes

  • Adding 1 instead of side[r][c] to the total: that only counts 1 x 1 squares (returning 13 instead of 20 on Example 1).
  • Returning max of side[r][c] instead of the sum: that finds the side length of the single largest square ("Maximal Square") rather than counting all squares.
  • Omitting the diagonal neighbor side[r - 1][c - 1]: checking only min(up, left) on [[0, 1], [1, 1]] computes 1 + min(1, 1) = 2 at (1, 1), falsely counting a 2 x 2 square that covers the top-left 0.
  • Using max(...) instead of min(...): a square is only as large as the smallest of its three supporting neighbor squares.
  • Forgetting r == 0 or c == 0 when mutating grid in place: in Python, negative index -1 wraps around to the last row or column instead of raising an IndexError, so grid[0 - 1][c] reads grid[rows - 1][c] and corrupts row 0 whenever the bottom row contains 1s!

Alternative approaches

  • 2D prefix sums (O(m * n * min(m, n)) time, O(m * n) space): a 2D prefix sum (a precomputed table storing the sum of every rectangle from (0, 0) to (r, c) so any sub-rectangle sum can be queried in O(1) time) lets you check whether a candidate k x k square sums to k * k in O(1) time, or binary-search the largest k per corner in O(m * n * log(min(m, n))) time — clean, but still slower and longer than the O(m * n) DP.
  • In-place DP (O(m * n) time, O(1) extra space): writing side values directly into grid[r][c] eliminates the separate table, at the cost of mutating the caller's input matrix.

Follow-up questions

  • How can you reduce the extra memory needed by the DP table from O(m * n) to O(n) or O(1)? Because computing row r only ever reads side[r - 1] (the previous row) and side[r] (the current row), keep just two 1D arrays prev_row and curr_row of length n + 1 (where index 0 stays a permanent 0 sentinel to eliminate the c == 0 check), reducing auxiliary space to O(n) without touching grid (or O(min(m, n)) if you iterate along the shorter dimension). To reach O(1) extra space, confirm with the interviewer that mutating grid is allowed, then overwrite grid[r][c] = 1 + min(grid[r - 1][c], grid[r][c - 1], grid[r - 1][c - 1]) directly for r > 0, c > 0, and grid[r][c] == 1.
  • What changes if you need to count every all-ones rectangle of any width and height instead of only squares? A single side length per cell is no longer enough because a tall thin rectangle and a short wide rectangle can both end at (r, c) without one containing the other. Instead, scan row by row maintaining heights[c] (the number of consecutive 1s extending upward from (r, c) in column c), turning each row into a histogram. For each row, walk left to right with a monotonic stack (a stack kept in strictly increasing order of heights by popping taller or equal bars) to find the nearest column p to the left with heights[p] < heights[c]: rectangles with left edge in (p, c] can all reach height heights[c] (heights[c] * (c - p) rectangles), while rectangles starting at or before p reuse ending[p], keeping total time O(m * n) and space O(n).
  • Suppose the matrix is too massive for RAM and is stored as fixed-size disk tiles — how would you count squares that span across tile borders? Notice that side[r][c] depends only on its immediate top, left, and top-left neighbors — it never needs the raw interior cells of earlier tiles! Partition the huge matrix into B x B tiles that fit comfortably in RAM: to process tile (tr, tc), feed it only the 1D bottom boundary row of side values from tile (tr - 1, tc) above, the 1D right boundary column of side values from tile (tr, tc - 1) to the left, and the single bottom-right corner side integer from tile (tr - 1, tc - 1) diagonally up-left. Those boundary numbers already encode how far 1s extend across earlier tiles, so running the exact same DP inside tile (tr, tc) counts every square whose bottom-right corner falls in that tile — including squares spanning multiple tiles! To parallelize across disks and machines, schedule tiles in anti-diagonal wavefronts (waves where tr + tc = 0, 1, 2, ... is constant), since all tiles on wave s depend only on boundary strips emitted by waves s - 1 and s - 2.

Follow-up questions

Similar questions

More Purestorage interview questions

All 4 Purestorage questions →