DSA Tracker

Medium

Count Square Submatrices with All Ones

A medium Dynamic Programming problem included in Striver A2Z. Below: the roles whose interviews prioritise this topic, and how to practise it.

Topic
Dynamic Programming
Sheets
1
Core for
9 roles
Platform
LeetCode

The problem

Given a 2D binary matrix, count the total number of square submatrices with all ones.

Example 1

Input
matrix = [[0,1,1,1],[1,1,1,1],[0,1,1,1]]
Output
15
Why
There are 10 squares of size 1, 4 squares of size 2, and 1 square of size 3, totaling 15.

Example 2

Input
matrix = [[1,0,1],[1,1,0],[1,1,0]]
Output
7
Why
5 squares of size 1 and 2 squares of size 2, totaling 7.

Example 3

Input
matrix = [[0,0],[0,0]]
Output
0
Why
No squares of ones exist.

Constraints

  • 1 <= matrix.length, matrix[i].length <= 300
  • matrix[i][j] is 0 or 1

How to think about it

Updated 2026-09-09

The side length of the largest all-ones square whose bottom-right corner rests at (i, j) is exactly equal to the number of square submatrices anchored at that corner. Because every larger square contains smaller squares inside it, summing dp[i][j] across all cells gives the total count.

Approaches, worst first

  1. Exhaustive corner expansion

    time O(m * n * min(m, n)) · space O(1)

    For every cell with value 1, test possible side lengths k from 1 upward, checking if all cells in the k x k square are 1. Inefficient due to repetitive cell scans.

  2. Corner-anchored dynamic programming

    time O(m * n) · space O(m * n)

    Let dp[i][j] be the side length of the largest square ending at (i, j). If matrix[i][j] == 1, dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) for i, j > 0. Accumulate all dp[i][j] values.

  3. 1D rolling array optimizationWrite this one

    time O(m * n) · space O(n)

    Compress the DP table to a single row array plus a variable storing the top-left diagonal cell. Reduces space to linear in column count while accumulating the running total.

Where people lose marks · 3
  • First row and first column handling: cells with matrix[i][j] == 1 on row 0 or col 0 can only ever form squares of size 1 (dp[i][j] = 1).
  • Confusing max square area with total square count: the task asks for the sum of all valid square sizes, not the single maximum square.
  • Overwriting diagonal predecessor state: during 1D row compression, the diagonal value dp[i-1][j-1] must be saved in a temporary variable before dp[j] is overwritten.

The theory behind it

Dynamic Programming — the ground this problem stands on. All Dynamic Programming problems

What Dynamic Programming is

Dynamic programming is a method for solving a complex problem by breaking it into overlapping subproblems, solving each subproblem only once, and remembering the answers in a lookup table. Instead of recalculating identical questions over and over, future steps look up previous answers directly. By assembling these saved pieces from the bottom up or storing them during recursion, a task that would take billions of steps finishes in a fraction of a second.

When to reach for it

Reach for dynamic programming when questions ask for the maximum profit, minimum cost, total number of distinct ways to achieve a goal, or whether a target can be formed. Signals include overlapping choices where making a choice now affects what choices remain later, but greedy picking fails to find the true global optimum. If drawing a recursive decision tree reveals the same subproblem states repeating across branches, dynamic programming is needed.

How the pattern works

Identify the state variables that uniquely describe a subproblem, such as an array index and remaining capacity. Write the base cases first, representing states whose answers are known without calculation. Next, write the recurrence relation that expresses the current state using previously solved states, taking the minimum, maximum, or sum among your options. Build the solution either top-down by caching recursive returns in a memo table, or bottom-up by filling an array in topological dependency order. When each state depends only on the previous row, compress storage down to a single array.

What each operation costs

OperationTime
fill dynamic programming table of n statesO(n)
solve two-dimensional grid of m by n statesO(m * n)
space-optimized state transition keeping one rowO(n)
What usually goes wrong with Dynamic Programming
  • Filling a bottom-up table in an order where the current cell needs values that have not been computed yet, reading uninitialized zeros.
  • Failing to initialize base cases properly, such as filling a minimization table with zeros instead of infinity, which traps the answer at zero.
  • Overwriting values in a 1D space-optimized knapsack array by scanning in the wrong direction, allowing the same item to be chosen multiple times.

Which roles need this problem

Dynamic Programming is a core topic for these 9 roles — if you're targeting one of them, this problem is early in your path, not optional.

Secondary for 5 more roles, including Game Developer, Cryptography Engineer, Performance Engineer.

Track this in your role's order

Pick your target role and all 370 problems — including this one — resequence to what that interview actually asks. Free.

Start free

More Dynamic Programming problems

Problem set and role mapping as of .