Count Square Submatrices with All Ones

MediumDynamic Programming2d dp

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

Given an m x n grid matrix of 0s and 1s, count every square submatrix (of any size, including 1 x 1) whose cells are all 1. Squares that overlap are counted separately, and a large square also contributes all the smaller squares inside it.

Examples

Input: matrix = [[0,1,1,1],[1,1,1,1],[0,1,1,1]]
Output: 15
There are 10 squares of side 1, 4 of side 2 and 1 of side 3.
Input: matrix = [[1,0,1],[1,1,0],[1,1,0]]
Output: 7
6 squares of side 1 and 1 of side 2.

Constraints

  • 1 <= m, n <= 300
  • `matrix[i][j]` is `0` or `1`

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More 2d dp problems