FastPrepCount All-One Squares
Problems/Count All-One Squares

Count All-One Squares

Google logoGoogle● MediumNEW GRADONSITE INTERVIEW
QuestionFunctionExamplesConstraints

Problem statement

Source note: The reported square-count variant matches at about 75%. “Total number” is interpreted as counting all qualifying squares; the binary input, overlap rule and numeric bounds are explicit practice details.

Given a nonempty rectangular binary matrix, return the number of square submatrices whose cells are all 1.

A square uses consecutive rows and consecutive columns. Count each distinct top-left position and side length once, including 1 x 1 squares. Overlapping squares are counted separately. Return a count of squares, rather than the largest area or the sum of their areas.

Function

countSquares(matrix: int[][]) → int

Examples

Example 1

matrix = [[1,1],[1,1]]return = 5

Four 1x1 squares and the one 2x2 square contribute five squares.

Example 2

matrix = [[1,1,1],[1,1,1]]return = 8

Six 1x1 squares and two overlapping 2x2 squares are counted.

Example 3

matrix = [[1,0],[0,1]]return = 2

Only the two isolated 1 cells are valid squares.

Constraints

  • 1 <= matrix.length, matrix[0].length <= 100.
  • Every row has the same length.
  • Every entry is 0 or 1.

More Google problems

  • Apartment Housemate PreferencesPHONE SCREEN · Seen Nov 2026
  • Apartment Housemate PreferencesPHONE SCREEN · Seen Nov 2026
  • Price at Query TimestampsPHONE SCREEN · Seen Nov 2026
All Google interview questionsSee Google hiring insights
Saved
class Solution {
    public int countSquares(int[][] matrix) {
        // Write your code here.
    }
}
Checking account…