Skip to main content

Maximal Square: The min-of-three DP Recurrence

Page 1

Maximal Square: The min-of-three DP Recurrence Maximal Square asks for the area of the largest square of 1s in a binary matrix. The brute force checks every top-left corner and every size, which is O((mn)^2). A clean DP brings it to O(mn).

The state Let dp[i][j] be the side length of the largest square of 1s whose bottom-right corner is at (i, j).

The recurrence If matrix[i][j] is 0, dp[i][j] is 0. Otherwise dp[i][j] = 1 + min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]). The square can only grow as far as its weakest neighbor allows: up, left, and the diagonal each limit one side. def maximal_square(matrix): if not matrix: return 0 cols = len(matrix[0]) dp = [0] * (cols + 1) best = 0 for row in matrix: prev = 0 for j in range(1, cols + 1): tmp = dp[j] if row[j - 1] == "1": dp[j] = 1 + min(dp[j], dp[j - 1], prev) best = max(best, dp[j]) else: dp[j] = 0 prev = tmp return best * best

Explaining it out loud Draw a 3 by 3 block of ones with one corner missing and fill in the table. Interviewers want to see that you understand why the minimum is correct, not just that you recall it.

Related problems Count Square Submatrices uses the same table and sums it. Maximal Rectangle is harder and uses the largest-rectangle-in-histogram stack per row. Practice tools for coding rounds: https://www.linkjob.ai/. Disclosure: I help build Linkjob AI.


Turn static files into dynamic content formats.

Create a flipbook
Maximal Square: The min-of-three DP Recurrence by linkjobai-max - Issuu