Count Square Submatrices with All Ones solution explained

Count Square Submatrices with All Ones asks how many square blocks of a grid of 0s and 1s are filled entirely with 1s, counting every size and every position. For each cell, the side of the largest all-ones square whose bottom-right corner is that cell equals the smallest of its top, left and top-left neighbors plus one, and that side is also the number of squares ending there. Summing the table gives the answer in O(m × n) time.

By Published 8 min read

The problem, in plain terms

You are given a rectangle of cells, each either 0 or 1. A square block is any k by k group of cells lined up with the grid. Count how many such blocks contain no 0 at all. A single 1 is a 1 by 1 block and counts. Blocks may overlap, and a big block's smaller pieces each count on their own.

Case A
  1 1 0 1
  1 1 1 1
  0 1 1 1
  1x1 blocks: 10   2x2 blocks: 3   3x3 blocks: 0
  answer: 13

Case B: a grid of only 0s         answer: 0
Case C: a 3 x 3 grid of only 1s   9 + 4 + 1 = 14
Three cases, made up for this page

Questions to ask: can the grid be empty or have rows of length zero? May you modify the input? Is the grid square, or any rectangle? (Any rectangle; never assume m equals n.) The answer for a large all-ones grid grows roughly with m × n × min(m, n), so check the integer type if sizes are big.

Why interviewers like it

It is a two-dimensional DP with a recurrence that is easy to state and easy to get subtly wrong. The interviewer is listening for two things: a convincing reason why the minimum of three neighbors gives the largest square, and the counting insight that the largest square at a corner also tells you how many squares end there. Candidates who know the largest-square problem often stop at the maximum and need a nudge to see they can sum instead.

Brute force: try every corner and size

For every top-left cell, grow the square one size at a time and check the new bottom row and right column. Stop growing as soon as a 0 appears, since every larger square from that corner contains it too. Counting each size that passes gives the answer. In the worst case, an all-ones grid, this is O(m × n × min(m, n)²), which is slow but simple and was the reference for testing.

def count_squares_brute(grid):
    rows = len(grid)
    cols = len(grid[0]) if rows else 0
    total = 0
    for r in range(rows):
        for c in range(cols):
            size = 0
            while r + size < rows and c + size < cols:
                edge_r, edge_c = r + size, c + size
                new_row = all(grid[edge_r][c + k] for k in range(size + 1))
                new_col = all(grid[r + k][edge_c] for k in range(size + 1))
                if not (new_row and new_col):
                    break
                size += 1
                total += 1
    return total
Python: grow each square from its top-left corner

Dynamic programming: the largest square ending at each cell

Let side[i][j] be the side length of the largest all-ones square whose bottom-right corner is (i, j). A 0 cell has side 0. For a 1 cell, a square of side s ending here needs a square of side s - 1 ending at the cell above, one ending at the cell to the left, and one ending at the cell diagonally up and left. Those three overlapping squares, plus the cell itself, cover the bigger square exactly. So the largest possible s is one more than the smallest of those three neighbors.

The counting step: if the largest square ending at (i, j) has side s, then the squares of side 1, 2, ..., s ending there are all valid, because each is the bottom-right corner piece of the big one, and no square of side s + 1 is. That is exactly s squares. Every square has one bottom-right corner, so summing side over all cells counts every square once.

def count_squares(grid):
    if not grid or not grid[0]:
        return 0
    cols = len(grid[0])
    prev = [0] * (cols + 1)  # padded: prev[c + 1] is the cell above column c
    total = 0
    for row in grid:
        cur = [0] * (cols + 1)
        for c in range(cols):
            if row[c] == 1:
                cur[c + 1] = 1 + min(prev[c + 1], cur[c], prev[c])
                total += cur[c + 1]
        prev = cur
    return total
Python: one row of DP, O(m × n) time, O(n) memory

The padding column of zeros means the first row and first column need no special case: their missing neighbors read as 0, so a 1 there gets side 1. If the interviewer allows changing the input, you can write each side directly into the grid and skip the extra rows. Say that you are doing it, since callers may not expect their grid to change.

function countSquaresInPlace(grid) {
  let total = 0;
  for (let r = 0; r < grid.length; r++) {
    for (let c = 0; c < grid[r].length; c++) {
      if (grid[r][c] === 1 && r > 0 && c > 0) {
        grid[r][c] = 1 + Math.min(grid[r - 1][c], grid[r][c - 1], grid[r - 1][c - 1]);
      }
      total += grid[r][c];
    }
  }
  return total;
}
JavaScript: in place, overwriting the grid with side lengths
  1 1 0 1
  1 2 1 1
  0 1 2 2
  row sums: 3 + 5 + 5 = 13
Case A as a table of sides

Look at the cell in the middle row, third column. Its left neighbor has side 2, but the cell above it is a 0, so it can only be the corner of a 1 by 1 square. That is the minimum doing its job: a big square on one side does not help if another side is blocked.

Complexity summary

m rows, n columns
ApproachTimeExtra memoryNote
Grow from every top-left cornerO(m × n × min(m, n)²)O(1)Reference only
Full DP tableO(m × n)O(m × n)Easiest to trace
One padded rowO(m × n)O(n)Leaves the input alone
In placeO(m × n)O(1)Overwrites the grid; ask first
m rows, n columns. Scroll sideways on a small screen.

Edge cases to try

  • Empty grid, or rows with no columns: 0.
  • A single row or single column: the answer is the number of 1s, since only 1 by 1 squares fit.
  • All 0s: 0. All 1s in an m by n grid: the sum over k of (m - k + 1) × (n - k + 1).
  • A wide grid such as 2 by 6, to catch code that assumes a square input.
  • A 0 in the corner of an otherwise full grid: it blocks every square that would contain it.

Mistakes to avoid

  • Using the maximum of the neighbors instead of the minimum.
  • Returning the largest side, which answers the largest-square question, not this one.
  • Adding side squared, or the area, instead of side.
  • Indexing r - 1 or c - 1 on the first row or column without padding or a guard.
  • Modifying the input without saying so, then reusing the grid elsewhere.

Follow-ups

  • Largest square only. Same table, return the maximum side, or its square for the area.
  • Count all-ones rectangles, not squares. A different technique: for each row, build column heights of consecutive 1s and count rectangles ending at each cell with a monotonic stack.
  • The grid streams in one row at a time. The one-row version already handles this.
  • Count squares with at most one 0. The simple min recurrence no longer applies; prefix sums with a size check per corner are a reasonable place to start.

How to explain it out loud

Fictional example

Turning a largest-square table into a count
Candidate
I will compute, for each cell, the biggest all-ones square that has this cell as its bottom-right corner.
Candidate
If the cell is a 1, that is one plus the smallest of the three neighbors above, left and diagonal, because the square needs all three of those to be at least one size smaller.
Interviewer
How does that help you count?
Candidate
If the biggest square at a corner has side three, then the squares of side one, two and three ending there all work. So each cell contributes its side, and every square has exactly one bottom-right corner. I sum the table.
Candidate
That is O(m times n). I can keep one padded row, or overwrite the grid if that is allowed.

Maximum Length of Repeated Subarray uses a cell that measures something ending at that cell, read from the diagonal. Arithmetic Slices applies the same count-what-ends-here idea to one dimension. Number of Islands is the other common grid question, solved with search instead of a table. The largest-square version of this problem is the natural pair to practice next.

Practicing it with Natively

This problem tests whether you can explain why a minimum of three neighbors is right, which is easier to judge from a transcript than from memory. Natively, a desktop app for Mac and Windows, can read a grid problem from a screenshot in practice and outline the side-length table, and the saved transcript of your mock round shows whether you made the counting argument clearly. Read more on the AI assistant for coding interviews page.

Questions people ask

How do you count square submatrices with all ones?

For each 1 cell, compute the side of the largest all-ones square whose bottom-right corner is that cell: one plus the smallest of the cells above, to the left and diagonally up-left. A 0 cell gets 0. The sum of all these sides is the number of squares.

Why does summing the side lengths count every square?

If the largest square ending at a cell has side s, then squares of side 1 through s also end there, which is exactly s squares. Every square has one bottom-right corner, so each is counted once.

What is the time complexity?

O(m × n) for an m by n grid. Extra memory is O(n) with one padded row, or O(1) if you may overwrite the grid with the side lengths.

How is it related to the largest square problem?

It uses the same table. The largest square problem returns the biggest side in the table; this problem returns the sum of all of them.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP