← Google Interview Insights

Google·Machine Learning Engineer·Onsite - Coding / Algorithms·Senior

SeniorPrefer not to say
Jun 2026

Summary

Google ML Engineer coding round, one question the whole time. The problem looked familiar but the twist tripped me up a bit before things clicked.

Questions Asked (1)

Q1

Given an m x n binary matrix, count the total number of square sub-matrices of any side length (at least 1x1) that are made up entirely of 1s.

Algorithms & Data Structures
Author's notes

I recognized this as related to the classic 'largest square of 1s' DP problem, which helped.

Create a free account to read the full note

AI HintsAI Generated

Suggested Approach

Use dynamic programming where dp[i][j] represents the side length of the largest all-1s square with bottom-right corner at (i, j). The total count of squares is the sum of all dp values, as each dp value counts all squares ending at that cell.

Pro tip: Clarify that the DP recurrence dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) works because a square of side k ending at (i,j) requires squares of side k-1 ending at the three neighboring cells. This demonstrates deep understanding and avoids off-by-one errors.

1. Define DP state

Let dp[i][j] be the side length of the largest all-1s square whose bottom-right corner is at cell (i, j). Initialize dp[i][j] = 0 for all cells.

2. Base cases and recurrence

For cells in the first row or first column, dp[i][j] = matrix[i][j] (since only 1x1 squares possible). For other cells, if matrix[i][j] == 1, dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]); else dp[i][j] = 0.

3. Compute total count

Sum all dp[i][j] values. Each dp[i][j] equals the number of squares with bottom-right corner at (i, j), so the sum gives the total number of all-1s squares.

4. Optimize space (optional)

If needed, reduce space complexity from O(m*n) to O(n) by keeping only the previous row and updating a 1D array. Mention this as an optimization.

5. Analyze complexity

Time complexity is O(m*n) as each cell is processed once. Space complexity is O(m*n) for the DP table, or O(n) with optimization.

Key Points to Mention

  • Dynamic programming approach with state definition
  • Recurrence relation: dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1])
  • Summing dp values to count all squares
  • Time and space complexity analysis
  • Space optimization to O(n) using a 1D array
  • Handling edge cases (empty matrix, all zeros, all ones)

AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.