Count Submatrices With All Ones

MediumMatrixmonotonic stack

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

You are given an m x n binary matrix mat containing only 0s and 1s. Count the axis-aligned rectangular submatrices (of any size, at any position) in which every cell is 1. Submatrices are distinguished by their position and dimensions. Return the count. O(m * n^2) is acceptable; O(m * n) with a monotonic stack is possible.

Examples

Input: mat = [[1,0,1],[1,1,0],[1,1,0]]
Output: 13
There are 6 of size 1x1, 2 of size 1x2, 3 of size 2x1, 1 of size 2x2, and 1 of size 3x1.
Input: mat = [[0,1,1,0],[0,1,1,1],[1,1,1,0]]
Output: 24
Counting all-ones rectangles of every shape gives 24.

Constraints

  • 1 <= m, n <= 150
  • mat[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 monotonic stack problems