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) <= 3001 <= len(grid[0]) <= 300(all rows have the same length)- Every entry
grid[r][c]is either0or1.
Step-by-step walkthrough
Understand the goal
We receive an
m x ngrid of0s and1s (1 <= m, n <= 300) and want the total count of square blocks filled exclusively with1s.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 = 20Why checking every square from scratch is too slow
A square is uniquely specified by its top-left corner
(r, c)and its side lengthk. What happens if we test every(r, c)and everykby scanning allk * kcells inside?- On a
300 x 300grid, there are300 * 300 = 90,000top-left corners. - Each corner can try up to
300side lengthsk. - Verifying one
k x ksquare reads up tok^2cells (90,000cells whenk = 300).
Summing
k^2 * (301 - k)^2acrossk = 1..300comes 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 the2k - 1newly added border cells, an all-1s300 x 300grid 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 same1s!- On a
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 lengthkof the largest all-1s square whose bottom-right corner is(r, c)(0ifgrid[r][c] == 0).Look at what happens when
side[r][c] == 3at(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 sidek, the smaller squares of side1, 2, ..., k - 1ending at(r, c)sit completely inside it — so allkof them are guaranteed to be all1s, 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 ofside[r][c]over every cell(r, c).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), soside[r][c] = 0. - If
grid[r][c] == 1andr == 0orc == 0(top row or left column), there is no room above or to the left for a2 x 2square, soside[r][c] = 1. - Otherwise (
grid[r][c] == 1,r > 0,c > 0), look at the three neighbor cellsup = (r - 1, c),left = (r, c - 1), andup_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 thek x ksquare! Therefore:- If all three neighbors have
side >= k - 1, every cell in thek x ksquare is1. - If any of the three neighbors has
side < k - 1, there is a0(or grid boundary) inside that region that also blocks thek x ksquare.
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])- If
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_squaresTrace through Example 1 cell by cell
Let's fill
sidefor 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 = 20Checking 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 1and2 x 2end here).(3, 3):up = 2,left = 2,up_left = 2->1 + min(2, 2, 2) = 3(1 x 1,2 x 2, and3 x 3all end here!).
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]]:
(0, 0)has value0->side[0][0] = 0(total = 0).(0, 1)has value1on row0->side[0][1] = 1(total = 1).(1, 0)has value1on column0->side[1][0] = 1(total = 2).(1, 1)has value1, withup = 1,left = 1,up_left = 0->side[1][1] = 1 + min(1, 1, 0) = 1(the0at(0, 0)blocks a2 x 2square!), givingtotal = 2 + 1 = 3.
Complexity
- Time: O(m * n), where
mis the number of rows andnis the number of columns. We visit each of them * ncells once and perform a constant O(1) amount of work per cell (one zero check, at most three array reads,minof three ints, and one addition). - Space: O(m * n) for the
sidetable ofmrows byncolumns, keeping the caller's inputgridunmodified. Because rowronly reads rowr - 1, auxiliary space can be reduced to O(n) using two 1D rows (see Follow-up 1).
Edge cases
1 x 1matrix:[[1]]hitsr == 0and returns1;[[0]]skips atgrid[r][c] == 0and returns0.- All
0s: every entry insidestays0, returning0. - All
1s (m x n): every sizekfrom1tomin(m, n)contributes(m - k + 1) * (n - k + 1)squares; for300 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 satisfiesr == 0 or c == 0, so only1 x 1squares count and the total equals the count of1s. - Single
0inside a sea of1s: itssideof0capsmin(up, left, up_left)for its right, bottom, and bottom-right neighbors, preventing any larger square from covering the0.
Common mistakes
- Adding
1instead ofside[r][c]to the total: that only counts1 x 1squares (returning13instead of20on Example 1). - Returning
maxofside[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 onlymin(up, left)on[[0, 1], [1, 1]]computes1 + min(1, 1) = 2at(1, 1), falsely counting a2 x 2square that covers the top-left0. - Using
max(...)instead ofmin(...): a square is only as large as the smallest of its three supporting neighbor squares. - Forgetting
r == 0 or c == 0when mutatinggridin place: in Python, negative index-1wraps around to the last row or column instead of raising anIndexError, sogrid[0 - 1][c]readsgrid[rows - 1][c]and corrupts row0whenever the bottom row contains1s!
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 candidatek x ksquare sums tok * kin O(1) time, or binary-search the largestkper corner inO(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): writingsidevalues directly intogrid[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
ronly ever readsside[r - 1](the previous row) andside[r](the current row), keep just two 1D arraysprev_rowandcurr_rowof lengthn + 1(where index0stays a permanent0sentinel to eliminate thec == 0check), reducing auxiliary space to O(n) without touchinggrid(orO(min(m, n))if you iterate along the shorter dimension). To reach O(1) extra space, confirm with the interviewer that mutatinggridis allowed, then overwritegrid[r][c] = 1 + min(grid[r - 1][c], grid[r][c - 1], grid[r - 1][c - 1])directly forr > 0,c > 0, andgrid[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 maintainingheights[c](the number of consecutive1s extending upward from(r, c)in columnc), turning each row into a histogram. For each row, walk left to right with a monotonic stack (a stack kept in strictly increasing order ofheightsby popping taller or equal bars) to find the nearest columnpto the left withheights[p] < heights[c]: rectangles with left edge in(p, c]can all reach heightheights[c](heights[c] * (c - p)rectangles), while rectangles starting at or beforepreuseending[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 intoB x Btiles that fit comfortably in RAM: to process tile(tr, tc), feed it only the 1D bottom boundary row ofsidevalues from tile(tr - 1, tc)above, the 1D right boundary column ofsidevalues from tile(tr, tc - 1)to the left, and the single bottom-right cornersideinteger from tile(tr - 1, tc - 1)diagonally up-left. Those boundary numbers already encode how far1s 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 wheretr + tc = 0, 1, 2, ...is constant), since all tiles on wavesdepend only on boundary strips emitted by wavess - 1ands - 2.
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)?
- What changes if you need to count every all-ones rectangle of any width and height instead of only squares?
- 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?
Similar questions
- Counting Squares from 2D Integer Coordinates
- Thread-Safe In-Memory Event Bus
- Thread-Safe One-Shot Latch
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses