{"id":"maximal-square","title":"Maximal Square","difficulty":"medium","patterns":["dp-2d"],"primaryConcept":"dp-2d-grid","concepts":["dp-2d-grid"],"problemForm":"core","companies":["Meta","Amazon","Google","Microsoft"],"category":"dynamic-programming","executionStyle":"solution-method","compareMode":"exact","syntheticTestConfig":{"inputShape":"matrix","primaryParam":"matrix","sizeMetric":"matrix-cells","constraints":["binary-string"],"sizes":[9,16,25,36]},"description":"Given an `m x n` binary matrix filled with `0` and `1` characters, return the area of the largest square containing only `1`s.","examples":[{"input":"matrix = [[\"1\",\"0\",\"1\",\"0\",\"0\"],[\"1\",\"0\",\"1\",\"1\",\"1\"],[\"1\",\"1\",\"1\",\"1\",\"1\"],[\"1\",\"0\",\"0\",\"1\",\"0\"]]","output":"4","explanation":"The largest all-1 square has side length 2, so its area is 4."},{"input":"matrix = [[\"0\",\"1\"],[\"1\",\"0\"]]","output":"1","explanation":"Each 1 is only a 1x1 square."}],"constraints":[{"id":"1-m-n-300","text":"1 <= m, n <= 300","check":[{"kind":"sizeRange","target":"matrix","measure":"matrixRows","min":1,"max":300},{"kind":"valueRange","target":"matrix","selector":"arrayItemLengths","min":1,"max":300}]},{"id":"matrix-i-j-is-either-0-or-1","text":"matrix[i][j] is either \"0\" or \"1\"","check":{"kind":"domain","target":"matrix","selector":"gridCells","allowed":["0","1"]}}],"starterCode":"class Solution:\n    def maximalSquare(self, matrix: list[list[str]]) -> int:\n        # Your code here\n        pass","functionName":"maximalSquare","testCases":[{"id":"1","input":{"matrix":[["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]},"expected":4,"description":"Canonical sample with a 2x2 square."},{"id":"2","input":{"matrix":[["0","1"],["1","0"]]},"expected":1,"description":"Only 1x1 squares exist."},{"id":"3","input":{"matrix":[["0"]]},"expected":0,"description":"No 1 cells."},{"id":"4","input":{"matrix":[["1","1","1"],["1","1","1"]]},"expected":4,"description":"A 2x2 square fits inside a rectangular all-1 matrix."},{"id":"5","input":{"matrix":[["1","1","0","1"]]},"expected":1,"description":"Single row can only form 1x1 squares."},{"id":"h1","input":{"matrix":[["1"]]},"expected":1,"description":"A single one-cell square has area one."},{"id":"h2","input":{"matrix":[["0","0"],["0","0"]]},"expected":0,"description":"All-zero matrices contain no square of ones."},{"id":"h3","input":{"matrix":[["1","1"],["1","1"]]},"expected":4,"description":"A 2x2 all-ones matrix has area four."},{"id":"h4","input":{"matrix":[["1","1","0"],["1","1","0"],["0","0","0"]]},"expected":4,"description":"A compact 2x2 block of ones sits in the corner."},{"id":"h5","input":{"matrix":[["0","1","1","1","0"],["1","1","1","1","0"],["1","1","1","1","0"],["0","1","1","1","0"]]},"expected":9,"description":"A 3x3 square is the largest all-ones region."},{"id":"single-column-ones","input":{"matrix":[["1"],["1"],["1"]]},"expected":1,"description":"A single-column matrix can only form 1x1 squares."},{"id":"interior-zero-blocks-large-square","input":{"matrix":[["1","1","1","1"],["1","1","1","1"],["1","1","0","1"],["1","1","1","1"]]},"expected":4,"description":"An interior zero prevents any 3x3 square even in a dense matrix."},{"id":"one-row-two-columns","input":{"matrix":[["0","1"]]},"expected":1,"description":"A single row with two columns, where only the second cell is a one."}],"hints":[{"level":1,"content":"Think about the largest square whose bottom-right corner is each cell."},{"level":2,"content":"A 1 cell can extend a square only if its top, left, and top-left DP neighbors can also support that size."},{"level":3,"content":"Use 1 + min(top, left, top-left), then square the largest side length seen."}],"guidedFlow":{"version":2,"approachSelection":{"contract":"approach-selection-v1","question":"Which approach should we implement?","decisionPrompt":"Choose the approach whose state and complexity match the problem constraints.","approaches":[{"id":"try-every-square","name":"Try every square","summary":"Enumerate possible top-left corners and side lengths, then scan each candidate square.","decisionReason":"Re-scanning every candidate square rechecks the same overlapping cells, so it runs near O(m*n*min(m,n)^3); the grid DP reuses three neighbor results and drops to O(m*n).","complexity":{"time":"O(m*n*min(m,n)^3)","space":"O(1)"},"tradeoffs":["Runs in O(m*n*min(m,n)^3) time and uses O(1) space."],"isOptimal":false},{"id":"grid-dp","name":"Grid DP recurrence","summary":"Store the largest all-1 square side length ending at each cell.","decisionReason":"Each cell reuses the three squares already computed above, to its left, and on the diagonal, so every square side is found in one constant-time step and the whole grid is filled in O(m*n) instead of rescanning overlapping candidates.","complexity":{"time":"O(m*n)","space":"O(m*n)"},"tradeoffs":["Runs in O(m*n) time and uses O(m*n) space."],"isOptimal":true}]},"codingCheckpoints":[{"id":"create-dp-table","title":"Create padded DP table","description":"Read both matrix dimensions and create a zero-filled table for bottom-right square side lengths.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"initializes_grid_dp_table","scope":"create-dp-table","readMode":"dp-value-query-v1","expected":{"firstAxisInputState":"matrix","secondAxisInputState":"matrix","firstAxisOffset":1,"secondAxisOffset":1}}]},"semanticSpec":{"intent":"Initialize a rectangular DP table for grid recurrence state.","doneWhen":"This step is done when a zero-filled two-dimensional state table is created from both matrix dimensions.","shouldFailWhen":"This step should fail if the solution keeps no per-cell recurrence state.","roles":["dp table","matrix dimensions"],"mustProve":["A two-dimensional zero-filled state table exists.","The table shape is derived from both matrix dimensions."],"mustNotAccept":["A scalar-only scan with no cell state."],"equivalentVariants":["Use a padded table or an equivalent grid-shaped DP table."],"proofSnippets":[{"id":"py-maximal-square-create-dp-table","language":"python","code":"class Solution:\n    def maximalSquare(self, matrix: list[list[str]]) -> int:\n        rows = len(matrix)\n        cols = len(matrix[0])\n        dp = [[0] * (cols + 1) for _ in range(rows + 1)]\n        return 0"}]},"commonMistakes":["Assuming the matrix is square","Aliasing rows by multiplying a nested list","Forgetting the padding row or column when using 1-based DP indices"],"hint":"Padding makes top, left, and top-left reads valid for the first real row and column."},{"id":"init-best","title":"Initialize best side","description":"Track the largest square side length seen so far.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"initializes_zero_numeric_state","scope":"init-count","readMode":"numeric-state-value-query-v1"}]},"semanticSpec":{"intent":"Initialize the numeric tracker for the best square side length.","doneWhen":"This step is done when a numeric best state starts at 0 before scanning cells.","shouldFailWhen":"This step should fail if no best side length is tracked.","roles":["best side length"],"mustProve":["A zero-initialized numeric state is prepared."],"mustNotAccept":["Returning a DP cell without tracking the maximum over all cells."],"equivalentVariants":["Name the state however you like as long as it tracks the best side length."],"proofSnippets":[{"id":"py-maximal-square-init-best","language":"python","code":"class Solution:\n    def maximalSquare(self, matrix: list[list[str]]) -> int:\n        rows = len(matrix)\n        cols = len(matrix[0])\n        dp = [[0] * (cols + 1) for _ in range(rows + 1)]\n        best = 0\n        best = best + 1\n        return best"}]},"commonMistakes":["Tracking area before the side length is known","Initializing best from one cell without checking whether it is 1"],"hint":"Start with no square found."},{"id":"nested-loops","title":"Scan every matrix cell","description":"Loop over the real matrix cells using the padded DP coordinates.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"loops_over_interior_grid","scope":"nested-loops","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Visit every cell whose bottom-right square size must be computed.","doneWhen":"This step is done when nested loops traverse the matrix-aligned DP cells.","shouldFailWhen":"This step should fail if only one row or one column is scanned.","roles":["row loop","column loop","dp cell"],"mustProve":["The code uses nested loops over both dimensions."],"mustNotAccept":["Scanning a flattened or single-axis subset only."],"equivalentVariants":["Use 1-based padded DP coordinates or 0-based matrix coordinates."],"proofSnippets":[{"id":"py-maximal-square-nested-loops","language":"python","code":"class Solution:\n    def maximalSquare(self, matrix: list[list[str]]) -> int:\n        rows = len(matrix)\n        cols = len(matrix[0])\n        dp = [[0] * (cols + 1) for _ in range(rows + 1)]\n        best = 0\n        best = best + 1\n        for r in range(1, rows + 1):\n            for c in range(1, cols + 1):\n                dp[r][c] = 0\n        return best"}]},"commonMistakes":["Skipping the first row or first column incorrectly","Looping over rows but not columns"],"hint":"Every cell can be the bottom-right corner of a square."},{"id":"dp-recurrence","title":"Apply square recurrence","description":"For a 1 cell, extend the smallest neighboring square by one.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"applies_tri_predecessor_extremum_with_offset","scope":"dp-transition-mismatch","readMode":"dp-value-query-v1"}]},"semanticSpec":{"intent":"Compute each all-1 square side length from top, left, and top-left DP predecessors.","doneWhen":"This step is done when a 1 cell writes 1 + min(top, left, top-left) into the DP table.","shouldFailWhen":"This step should fail if the diagonal predecessor is ignored or the recurrence uses max instead of min.","roles":["top predecessor","left predecessor","top-left predecessor","current square side"],"mustProve":["The recurrence reads three neighboring DP states.","The update adds one to their minimum."],"mustNotAccept":["Using only two neighbors.","Counting a rectangle instead of a square."],"equivalentVariants":["Use a padded table or shift the neighbor indices for an unpadded table."],"proofSnippets":[{"id":"py-maximal-square-dp-recurrence","language":"python","code":"class Solution:\n    def maximalSquare(self, matrix: list[list[str]]) -> int:\n        rows = len(matrix)\n        cols = len(matrix[0])\n        dp = [[0] * (cols + 1) for _ in range(rows + 1)]\n        best = 0\n        best = best + 1\n        for r in range(1, rows + 1):\n            for c in range(1, cols + 1):\n                if matrix[r - 1][c - 1] == \"1\":\n                    dp[r][c] = min(dp[r - 1][c], dp[r][c - 1], dp[r - 1][c - 1]) + 1\n        return best"}]},"commonMistakes":["Using max instead of min","Forgetting the top-left neighbor"],"hint":"A bigger square needs all three neighboring squares to support it."},{"id":"track-best","title":"Track largest side","description":"Update the best side length after each DP cell is computed.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"updates_numeric_extremum_state","scope":"track-best","readMode":"numeric-state-value-query-v1"}]},"semanticSpec":{"intent":"Keep the maximum side length found anywhere in the matrix.","doneWhen":"This step is done when the best numeric state is updated from the current DP cell.","shouldFailWhen":"This step should fail if only the bottom-right DP cell is considered.","roles":["best side length","current DP side length"],"mustProve":["The best state is updated with an extremum operation."],"mustNotAccept":["Returning only the last computed side length."],"equivalentVariants":["Track max side length or track max area from the same DP cell updates."],"proofSnippets":[{"id":"py-maximal-square-track-best","language":"python","code":"class Solution:\n    def maximalSquare(self, matrix: list[list[str]]) -> int:\n        rows = len(matrix)\n        cols = len(matrix[0])\n        dp = [[0] * (cols + 1) for _ in range(rows + 1)]\n        best = 0\n        for r in range(1, rows + 1):\n            for c in range(1, cols + 1):\n                if matrix[r - 1][c - 1] == \"1\":\n                    dp[r][c] = min(dp[r - 1][c], dp[r][c - 1], dp[r - 1][c - 1]) + 1\n                    best = max(best, dp[r][c])\n        return 0"}]},"commonMistakes":["Updating best before computing the DP cell","Only checking the final row"],"hint":"The largest square can end at any cell, so update the best side after each DP cell."},{"id":"return-area","title":"Return square area","description":"Return the area from the best side length.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"numeric-state","fact":"returns_extremum_numeric_state","scope":"return-profit","readMode":"numeric-state-value-query-v1"}]},"semanticSpec":{"intent":"Return the final answer using the extremum state computed during the scan.","doneWhen":"This step is done when the function returns the best side length squared.","shouldFailWhen":"This step should fail if the function returns the side length instead of area.","roles":["best side length","area"],"mustProve":["The returned value is derived from the tracked extremum state."],"mustNotAccept":["Returning the side length directly."],"equivalentVariants":["Return best * best or maintain and return an equivalent best area."],"proofSnippets":[{"id":"py-maximal-square-return-area","language":"python","code":"class Solution:\n    def maximalSquare(self, matrix: list[list[str]]) -> int:\n        rows = len(matrix)\n        cols = len(matrix[0])\n        dp = [[0] * (cols + 1) for _ in range(rows + 1)]\n        best = 0\n        for r in range(1, rows + 1):\n            for c in range(1, cols + 1):\n                if matrix[r - 1][c - 1] == \"1\":\n                    dp[r][c] = min(dp[r - 1][c], dp[r][c - 1], dp[r - 1][c - 1]) + 1\n                    best = max(best, dp[r][c])\n        return best * best"}]},"commonMistakes":["Returning side length instead of area","Returning a DP table cell instead of the tracked best"],"hint":"The answer asks for area, so square the side length."}],"slides":[{"id":"read-the-signal","kind":"info","chapter":"The grid","eyebrow":"Read the problem","title":"The biggest solid square of ones","workspacePanel":"problem","body":["You are given a grid of 0s and 1s. The job is the area of the largest square block that is filled entirely with 1s.","A square ending at a 1 can grow only as far as the squares ending above it, left of it, and diagonally above-left all allow. One smaller neighbor limits the whole square."]},{"id":"try-every-square","kind":"code-trace","chapter":"The obvious way","eyebrow":"The obvious way","title":"Test every square you can draw","workspacePanel":"trace","summary":"Drawing every square from every corner and scanning it for a stray 0 is correct, but each candidate is checked from scratch. Watch how much of a square the scan re-walks before it can judge it.","codeTrace":{"contract":"code-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"rows = len(matrix)\ncols = len(matrix[0])\nbest = 0\nfor r in range(rows):\n    for c in range(cols):\n        side = 1\n        while r + side <= rows and c + side <= cols:\n            solid = True\n            for i in range(r, r + side):\n                for j in range(c, c + side):\n                    if matrix[i][j] == \"0\":\n                        solid = False\n            if solid:\n                best = max(best, side)\n            side += 1\nreturn best * best","steps":[{"id":"pick-corner","title":"Pick a top-left corner","codeLine":5,"summary":"Start at cell (0,0) and try squares that grow down and to the right from it.","state":{"grid":[[1,1,1],[1,1,1],[0,1,1]],"r":0,"c":0,"best":0,"labels":{"grid":"matrix"}}},{"id":"scan-side-one","title":"Side 1: scan the single cell","codeLine":11,"summary":"side = 1 walks the one cell (0,0). It is a 1, so best becomes 1.","state":{"grid":[[1,1,1],[1,1,1],[0,1,1]],"r":0,"c":0,"side":1,"best":1,"filled":[[0,0]],"labels":{"grid":"matrix"},"changed":[]}},{"id":"scan-side-two","title":"Side 2: scan all four cells","codeLine":11,"summary":"side = 2 walks (0,0), (0,1), (1,0), (1,1). All four are 1, so best becomes 2.","state":{"grid":[[1,1,1],[1,1,1],[0,1,1]],"r":0,"c":0,"side":2,"best":2,"filled":[[0,0],[0,1],[1,0],[1,1]],"labels":{"grid":"matrix"},"changed":[]}},{"id":"next-corner","title":"Move the corner and start over","codeLine":5,"summary":"Corner (0,1) begins its own side-1 then side-2 scans, walking (0,1), (0,2), (1,1), (1,2) again.","state":{"grid":[[1,1,1],[1,1,1],[0,1,1]],"r":0,"c":1,"side":2,"best":2,"filled":[[0,1],[0,2],[1,1],[1,2]],"labels":{"grid":"matrix"},"changed":[]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const rows = matrix.length;\nconst cols = matrix[0].length;\nlet best = 0;\nfor (let r = 0; r < rows; r++) {\n    for (let c = 0; c < cols; c++) {\n        let side = 1;\n        while (((r + side) <= rows) && ((c + side) <= cols)) {\n            let solid = true;\n            for (let i = r; i < (r + side); i++) {\n                for (let j = c; j < (c + side); j++) {\n                    if (matrix[i][j] === \"0\") {\n                        solid = false;\n                    }\n                }\n            }\n            if (solid) {\n                best = Math.max(best, side);\n            }\n            side++;\n        }\n    }\n}\nreturn (best * best);","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10,"11":11,"12":12,"13":16,"14":17,"15":19,"16":23},"statementBundles":{"12":{"startLine":12,"endLine":15},"14":{"startLine":17,"endLine":18},"15":{"startLine":19,"endLine":22}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const rows = matrix.length;\nconst cols = matrix[0].length;\nlet best = 0;\nfor (let r = 0; r < rows; r++) {\n    for (let c = 0; c < cols; c++) {\n        let side = 1;\n        while (((r + side) <= rows) && ((c + side) <= cols)) {\n            let solid = true;\n            for (let i = r; i < (r + side); i++) {\n                for (let j = c; j < (c + side); j++) {\n                    if (matrix[i][j] === \"0\") {\n                        solid = false;\n                    }\n                }\n            }\n            if (solid) {\n                best = Math.max(best, side);\n            }\n            side++;\n        }\n    }\n}\nreturn (best * best);","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10,"11":11,"12":12,"13":16,"14":17,"15":19,"16":23},"statementBundles":{"12":{"startLine":12,"endLine":15},"14":{"startLine":17,"endLine":18},"15":{"startLine":19,"endLine":22}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"int rows = matrix.size();\nint cols = matrix.get(0).size();\nint best = 0;\nfor (int r = 0; r < rows; r++) {\n    for (int c = 0; c < cols; c++) {\n        int side = 1;\n        while (((r + side) <= rows && (c + side) <= cols)) {\n            boolean solid = true;\n            for (int i = r; i < (r + side); i++) {\n                for (int j = c; j < (c + side); j++) {\n                    if (\"0\".equals(matrix.get(i).get(j))) {\n                        solid = false;\n                    }\n                }\n            }\n            if (solid) {\n                best = Math.max(best, side);\n            }\n            side++;\n        }\n    }\n}\nreturn (best * best);","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10,"11":11,"12":12,"13":16,"14":17,"15":19,"16":23},"statementBundles":{"12":{"startLine":12,"endLine":15},"14":{"startLine":17,"endLine":18},"15":{"startLine":19,"endLine":22}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int rows = matrix.Count;\nint cols = matrix[0].Count;\nint best = 0;\nfor (int r = 0; r < rows; r++) {\n    for (int c = 0; c < cols; c++) {\n        int side = 1;\n        while (r + side <= rows && c + side <= cols) {\n            bool solid = true;\n            for (int i = r; i < r + side; i++) {\n                for (int j = c; j < c + side; j++) {\n                    if (matrix[i][j] == \"0\") {\n                        solid = false;\n                    }\n                }\n            }\n            if (solid) {\n                best = Math.Max(best, side);\n            }\n            side++;\n        }\n    }\n}\nreturn best * best;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10,"11":11,"12":12,"13":16,"14":17,"15":19,"16":23},"statementBundles":{"12":{"startLine":12,"endLine":15},"14":{"startLine":17,"endLine":18},"15":{"startLine":19,"endLine":22}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"int rows = matrix.size();\nint cols = matrix[0].size();\nint best = 0;\nfor (int r = 0; r < rows; r++) {\n    for (int c = 0; c < cols; c++) {\n        int side = 1;\n        while (((r + side) <= rows && (c + side) <= cols)) {\n            bool solid = true;\n            for (int i = r; i < (r + side); i++) {\n                for (int j = c; j < (c + side); j++) {\n                    if (matrix[i][j] == string(\"0\")) {\n                        solid = false;\n                    }\n                }\n            }\n            if (solid) {\n                best = max(best, side);\n            }\n            side++;\n        }\n    }\n}\nreturn (best * best);","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10,"11":11,"12":12,"13":16,"14":17,"15":19,"16":23},"statementBundles":{"12":{"startLine":12,"endLine":15},"14":{"startLine":17,"endLine":18},"15":{"startLine":19,"endLine":22}}}}}},{"id":"repeated-work","kind":"case-probe","chapter":"The obvious way","eyebrow":"Name the waste","title":"How much work does each candidate square cost on its own?","workspacePanel":"trace","summary":"The inner two loops re-walk every cell of a candidate before judging it.","options":[{"id":"rescan","label":"It rescans every cell of the square, so a side-k candidate is k by k checks redone from scratch","rationale":"The side-2 scan walked four cells the side-1 scan had already touched, and the next corner walks the same overlapping cells again, so each candidate pays its full area in checks.","isCorrect":true},{"id":"constant","label":"A constant amount, since it only checks the new outer ring","rationale":"The code has no memory of the previous scan: the inner loops run over the whole side-by-side block every time, including old cells and the new edge."},{"id":"compare","label":"Just one comparison against the running best","rationale":"Updating best is one comparison, but it happens only after the inner loops have already re-walked the entire candidate block."}],"answer":"It rescans the whole square: a side-k candidate is k by k cell checks, and overlapping candidates redo those same cells over and over."},{"id":"three-neighbours","kind":"case-probe","chapter":"The idea","eyebrow":"Find the structure","title":"For a 1 cell to close off a 2x2 square, which cells must already be 1?","workspacePanel":"visualizer","summary":"The highlighted cell is a 1, and a 2x2 block would close off using it as the bottom-right corner.","options":[{"id":"three","label":"The cell above it, the cell to its left, and the cell diagonally up-left","rationale":"A 2x2 ending here is exactly those four cells, so the other three corners, above, left, and the diagonal, must all be 1.","isCorrect":true},{"id":"two","label":"Only the cell above and the cell to its left","rationale":"Above and left are two corners, but the fourth corner of the block is the diagonal cell, which also has to be a 1."},{"id":"row","label":"The whole row to its left","rationale":"A square is two-dimensional. A full row describes a wide strip; the compact block also needs the cell above and the diagonal."}],"answer":"Above, left, and the diagonal up-left. Those three plus this cell are the four corners of the 2x2 block.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"three-state","state":{"grid":[[1,1,0],[1,1,0],[0,0,0]],"r":1,"c":1,"filled":[[0,0],[0,1],[1,0]],"labels":{"grid":"matrix"},"changed":[]}}]}},{"id":"min-rule","kind":"case-probe","chapter":"The idea","eyebrow":"Find the rule","title":"Given the biggest squares ending above, left, and diagonal, how big a square ends here?","workspacePanel":"visualizer","summary":"Let each filled cell hold the side of the biggest all-ones square that ends on it. This cell is a 1; its neighbors hold 2 above, 1 to the left, and 2 on the diagonal.","options":[{"id":"min","label":"One more than the smallest of the three neighbors","rationale":"The new square can only be as wide as the tightest neighbor allows, so 1 + min(2, 1, 2) = 2: the left neighbor at 1 caps it.","isCorrect":true},{"id":"max","label":"One more than the largest of the three neighbors","rationale":"Taking the largest would claim a 3-wide square, but the left neighbor only supports a 1-wide run, so the block would not be solid."},{"id":"sum","label":"One more than the three neighbors added together","rationale":"The square grows by a single ring of cells, not by stacking the neighbors, so it is bounded by one neighbor, not their total."}],"answer":"One more than the smallest neighbor. 1 + min(2, 1, 2) = 2, because the weakest of the three corners caps how far the square can extend.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"min-state","state":{"grid":[[1,1,1],[1,2,2],[0,1,1]],"r":2,"c":2,"filled":[[0,0],[0,1],[0,2],[1,0],[1,1],[1,2],[2,1]],"labels":{"grid":"dp"},"changed":[]}}]}},{"id":"approach-selection","kind":"choice","source":"approach-selection","chapter":"The idea","eyebrow":"Pick the approach","title":"Which shape should we build?","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"approach-structure","state":{"grid":[[1,1,1],[1,1,1],[0,1,1]],"r":0,"c":0,"filled":[[0,0]],"labels":{"grid":"matrix"},"changed":[]}}]}},{"id":"dry-run-setup","kind":"info","chapter":"Trace","eyebrow":"Watch it move","title":"Each cell remembers its biggest square","workspacePanel":"visualizer","body":["Give every cell a number: the side of the biggest all-ones square whose bottom-right corner is that cell. A 0 cell is 0, and any 1 on the top row or left column can only ever be 1.","With that border in place, sweep left to right and top to bottom. Each 1 cell becomes one more than the smallest of its three already-filled neighbors."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"setup-state","state":{"grid":[[1,1,1],[1,1,1],[0,1,1]],"r":1,"c":0,"filled":[[0,0],[0,1],[0,2],[1,0]],"labels":{"grid":"dp"},"changed":[]}}]}},{"id":"trace","kind":"dry-run","source":"trace-example","chapter":"Trace","eyebrow":"Fill the table","title":"Fill the biggest-square table","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"center","state":{"grid":[[1,1,1],[1,2,0],[0,0,0]],"r":1,"c":1,"filled":[[0,0],[0,1],[0,2],[1,0],[1,1]],"labels":{"grid":"dp"},"changed":[]}},{"id":"row1-right","state":{"grid":[[1,1,1],[1,2,2],[0,0,0]],"r":1,"c":2,"filled":[[0,0],[0,1],[0,2],[1,0],[1,1],[1,2]],"labels":{"grid":"dp"},"changed":[]}},{"id":"row2-mid","state":{"grid":[[1,1,1],[1,2,2],[0,1,0]],"r":2,"c":1,"filled":[[0,0],[0,1],[0,2],[1,0],[1,1],[1,2],[2,0],[2,1]],"labels":{"grid":"dp"},"changed":[]}},{"id":"corner","state":{"grid":[[1,1,1],[1,2,2],[0,1,2]],"r":2,"c":2,"filled":[[0,0],[0,1],[0,2],[1,0],[1,1],[1,2],[2,0],[2,1],[2,2]],"labels":{"grid":"dp"},"changed":[]}}]},"beats":[{"id":"center","title":"Cell (1,1): above 1, left 1, diagonal 1, and it is a 1. What lands here?","summary":"The first interior 1 cell.","prompt":"All three neighbors hold 1.","options":[{"id":"two","label":"2 = 1 + min(1, 1, 1)","rationale":"All three corners already support a 1-wide square, so this cell closes a 2x2 and stores 2.","isCorrect":true},{"id":"one","label":"1, the cell is on its own","rationale":"The three neighbors are all 1, so they each back a square. This cell extends them into a 2x2 rather than standing alone."},{"id":"four","label":"4, the area of the block","rationale":"The cell stores a side length. The 2x2 here has side 2; the squaring happens only at the very end."}],"answer":"2. Every neighbor is 1, so 1 + min(1, 1, 1) = 2 and a 2x2 square ends here."},{"id":"row1-right","title":"Cell (1,2): above 1, left 2, diagonal 1, and it is a 1. What lands here?","summary":"The neighbors are no longer equal.","prompt":"The left neighbor holds 2, but the other two hold 1.","options":[{"id":"two","label":"2 = 1 + min(1, 2, 1)","rationale":"The weakest neighbor is 1, so the square can only reach side 2 even though the left neighbor is wider.","isCorrect":true},{"id":"three","label":"3 = 1 + max(1, 2, 1)","rationale":"Taking the largest neighbor assumes the others back it, but the top and diagonal only support 1, so the block would not be solid."},{"id":"one","label":"1, it starts over","rationale":"Every neighbor is at least 1, so this 1 cell extends them to at least a 2x2 rather than restarting."}],"answer":"2. The smallest neighbor is 1, so 1 + min(1, 2, 1) = 2. A wider neighbor cannot help if the others lag."},{"id":"row2-mid","title":"Cell (2,1): above 2, left 0, diagonal 1, and it is a 1. What lands here?","summary":"A 0 neighbor sits to the left.","prompt":"The cell to the left holds 0 because the grid has a 0 in that corner.","options":[{"id":"one","label":"1 = 1 + min(2, 0, 1)","rationale":"The left neighbor is 0, so no square wider than a single cell can be solid here, and the cell stores 1.","isCorrect":true},{"id":"three","label":"3 = 1 + 2","rationale":"That uses only the top neighbor. The left neighbor at 0 vetoes any larger square, so the min is 0."},{"id":"zero","label":"0, a neighbor is 0","rationale":"The cell itself is a 1, so it always backs at least a 1x1 square; a 0 neighbor only stops it from growing past that."}],"answer":"1. The left neighbor is 0, so 1 + min(2, 0, 1) = 1. One weak corner pins the square back to a single cell."},{"id":"corner","title":"Cell (2,2): above 2, left 1, diagonal 2, and it is a 1. The biggest side?","summary":"The last cell, where two neighbors are large but one is not.","prompt":"Above and diagonal both hold 2, but the left neighbor holds 1.","options":[{"id":"two","label":"2 = 1 + min(2, 1, 2)","rationale":"Two neighbors support a 2-wide square, but the left neighbor only reaches 1, so the square caps at side 2.","isCorrect":true},{"id":"three","label":"3 = 1 + min(2, 2)","rationale":"Dropping the left neighbor claims a 3x3, but that block includes the 0 corner, so it is not solid."},{"id":"one","label":"1, the left neighbor wins","rationale":"The left neighbor is 1, so 1 + 1 = 2, not 1. The smallest is taken before adding the cell, not after."}],"answer":"2. 1 + min(2, 1, 2) = 2. The biggest side seen anywhere is 2, so the area is 2 squared, 4."}]},{"id":"drop-diagonal-pitfall","kind":"pitfall","chapter":"Trace","eyebrow":"Spot the trap","workspacePanel":"trace","title":"Could just the cell above and the cell to the left be enough?","summary":"Above and left are the two directions a square grows into, so reading only those two neighbors looks like enough, and on a solid block it gives the same answer. Watch what it writes when the corner those two share is a 0.","pitfall":"The code below takes 1 + min(top, left), leaving out the diagonal neighbor.","whyItMatters":"The cell's diagonal neighbor is the only one that can see the 0 sitting kitty-corner. Here top and left both read 1, so 1 + min(1, 1) = 2 claims a 2x2 square, but the diagonal holds 0 and the real block has a hole in its corner. Reading all three would have made min 0 and capped this cell at 1. The fix is dp[r][c] = 1 + min(top, left, top-left).","negativeTrace":{"contract":"negative-trace-v1","languageLabel":"Python","editorLanguage":"python","code":"rows = len(matrix)\ncols = len(matrix[0])\ndp = [[0] * cols for _ in range(rows)]\nbest = 0\nfor r in range(rows):\n    for c in range(cols):\n        if matrix[r][c] == \"1\":\n            if r == 0 or c == 0:\n                dp[r][c] = 1\n            else:\n                top = dp[r - 1][c]\n                left = dp[r][c - 1]\n                side = top\n                if left < side:\n                    side = left\n                dp[r][c] = side + 1\n            best = max(best, dp[r][c])\nreturn best * best","steps":[{"id":"before","title":"A 0 sits in the top-left corner","codeLine":7,"summary":"The grid is [[0,1],[1,1]]. The 0 corner means no 2x2 square is solid, so the real answer is side 1.","state":{"grid":[[0,1],[1,1]],"r":1,"c":1,"filled":[],"labels":{"grid":"dp"},"changed":[]}},{"id":"border-filled","title":"The border cells each fill in 1","codeLine":9,"summary":"The 0 cell stays 0. The two edge 1 cells have no square behind them, so each writes 1.","state":{"grid":[[0,1],[1,0]],"r":1,"c":0,"filled":[[0,0],[0,1],[1,0]],"labels":{"grid":"dp"},"changed":[]}},{"id":"read-two","title":"At the bottom-right: top reads 1, left reads 1","codeLine":12,"summary":"The two neighbors the code looks at both hold 1. The diagonal corner holds 0, but this code never reads it.","state":{"grid":[[0,1],[1,0]],"r":1,"c":1,"filled":[[0,1],[1,0]],"labels":{"grid":"dp"},"changed":[]}},{"id":"overclaim","title":"It writes side + 1 = 2 into the corner","codeLine":16,"summary":"min(1, 1) is 1, so the cell writes 2 and claims a 2x2 square, even though the 0 corner means no solid 2x2 exists.","state":{"grid":[[0,1],[1,2]],"r":1,"c":1,"filled":[[1,1]],"labels":{"grid":"dp"},"changed":[]}},{"id":"wrong-area","title":"It reports area 4; the real answer is 1","codeLine":18,"summary":"The best side is now 2, so the function squares it to 4, but the only solid square in this grid is a single cell.","state":{"grid":[[0,1],[1,2]],"r":1,"c":1,"filled":[[1,1]],"labels":{"grid":"dp"},"changed":[]}}],"localizations":{"javascript":{"languageLabel":"JavaScript","editorLanguage":"javascript","codeStyle":"natural","code":"const rows = matrix.length;\nconst cols = matrix[0].length;\nconst dp = Array.from({ length: rows }, () => Array(cols).fill(0));\nlet best = 0;\nfor (let r = 0; r < rows; r++) {\n    for (let c = 0; c < cols; c++) {\n        if (matrix[r][c] === \"1\") {\n            if (r === 0 || c === 0) {\n                dp[r][c] = 1;\n            } else {\n                const top = dp[(r - 1)][c];\n                const left = dp[r][(c - 1)];\n                let side = top;\n                if (left < side) {\n                    side = left;\n                }\n                dp[r][c] = (side + 1);\n            }\n            best = Math.max(best, dp[r][c]);\n        }\n    }\n}\nreturn (best * best);","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10,"11":11,"12":12,"13":13,"14":14,"15":15,"16":17,"17":19,"18":23},"statementBundles":{"15":{"startLine":15,"endLine":16},"16":{"startLine":17,"endLine":18},"17":{"startLine":19,"endLine":22}}},"typescript":{"languageLabel":"TypeScript","editorLanguage":"typescript","codeStyle":"natural","code":"const rows = matrix.length;\nconst cols = matrix[0].length;\nconst dp = Array.from({ length: rows }, () => Array(cols).fill(0));\nlet best = 0;\nfor (let r = 0; r < rows; r++) {\n    for (let c = 0; c < cols; c++) {\n        if (matrix[r][c] === \"1\") {\n            if (r === 0 || c === 0) {\n                dp[r][c] = 1;\n            } else {\n                const top = dp[(r - 1)][c];\n                const left = dp[r][(c - 1)];\n                let side = top;\n                if (left < side) {\n                    side = left;\n                }\n                dp[r][c] = (side + 1);\n            }\n            best = Math.max(best, dp[r][c]);\n        }\n    }\n}\nreturn (best * best);","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10,"11":11,"12":12,"13":13,"14":14,"15":15,"16":17,"17":19,"18":23},"statementBundles":{"15":{"startLine":15,"endLine":16},"16":{"startLine":17,"endLine":18},"17":{"startLine":19,"endLine":22}}},"java":{"languageLabel":"Java","editorLanguage":"java","codeStyle":"natural","code":"int rows = matrix.size();\nint cols = matrix.get(0).size();\nList<List<Integer>> dp = new ArrayList<>();\nfor (int i = 0; i < rows; i++) {\n    List<Integer> items0 = new ArrayList<>();\n    for (int index = 0; index < cols; index++) {\n        items0.add(0);\n    }\n    dp.add(items0);\n}\nint best = 0;\nfor (int r = 0; r < rows; r++) {\n    for (int c = 0; c < cols; c++) {\n        if (\"1\".equals(matrix.get(r).get(c))) {\n            if (r == 0 || c == 0) {\n                dp.get(r).set(c, 1);\n            } else {\n                int top = dp.get(r - 1).get(c);\n                int left = dp.get(r).get(c - 1);\n                int side = top;\n                if (left < side) {\n                    side = left;\n                }\n                dp.get(r).set(c, (side + 1));\n            }\n            best = Math.max(best, dp.get(r).get(c));\n        }\n    }\n}\nreturn (best * best);","lineMap":{"1":1,"2":2,"3":3,"4":11,"5":12,"6":13,"7":14,"8":15,"9":16,"10":17,"11":18,"12":19,"13":20,"14":21,"15":22,"16":24,"17":26,"18":30},"statementBundles":{"3":{"startLine":3,"endLine":10},"15":{"startLine":22,"endLine":23},"16":{"startLine":24,"endLine":25},"17":{"startLine":26,"endLine":29}}},"csharp":{"languageLabel":"C#","editorLanguage":"csharp","codeStyle":"natural","code":"int rows = matrix.Count;\nint cols = matrix[0].Count;\nList<List<int>> dp = Enumerable.Range(0, rows).Select(_ => Enumerable.Repeat<int>(0, cols).ToList()).ToList();\nint best = 0;\nfor (int r = 0; r < rows; r++) {\n    for (int c = 0; c < cols; c++) {\n        if (matrix[r][c] == \"1\") {\n            if (r == 0 || c == 0) {\n                dp[r][c] = 1;\n            } else {\n                int top = dp[r - 1][c];\n                int left = dp[r][c - 1];\n                int side = top;\n                if (left < side) {\n                    side = left;\n                }\n                dp[r][c] = side + 1;\n            }\n            best = Math.Max(best, dp[r][c]);\n        }\n    }\n}\nreturn best * best;","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10,"11":11,"12":12,"13":13,"14":14,"15":15,"16":17,"17":19,"18":23},"statementBundles":{"15":{"startLine":15,"endLine":16},"16":{"startLine":17,"endLine":18},"17":{"startLine":19,"endLine":22}}},"cpp":{"languageLabel":"C++","editorLanguage":"cpp","codeStyle":"natural","code":"int rows = matrix.size();\nint cols = matrix[0].size();\nvector<vector<int>> dp = vector<vector<int>>(rows, vector<int>(cols, 0));\nint best = 0;\nfor (int r = 0; r < rows; r++) {\n    for (int c = 0; c < cols; c++) {\n        if (matrix[r][c] == string(\"1\")) {\n            if ((r == 0 || c == 0)) {\n                dp[r][c] = 1;\n            } else {\n                int top = dp[(r - 1)][c];\n                int left = dp[r][(c - 1)];\n                int side = top;\n                if (left < side) {\n                    side = left;\n                }\n                dp[r][c] = (side + 1);\n            }\n            best = max(best, dp[r][c]);\n        }\n    }\n}\nreturn (best * best);","lineMap":{"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"10":10,"11":11,"12":12,"13":13,"14":14,"15":15,"16":17,"17":19,"18":23},"statementBundles":{"15":{"startLine":15,"endLine":16},"16":{"startLine":17,"endLine":18},"17":{"startLine":19,"endLine":22}}}}}},{"id":"edge-case-intro","kind":"info","chapter":"Edge cases","eyebrow":"Try to break it","title":"Which inputs could break this?","workspacePanel":"visualizer","body":["Each 1 cell taking one more than its smallest of three neighbors filled the whole grid once the border was seeded.","The thin and empty grids are where the rule gets stress-tested, so try a grid with no 1 at all, and a single-row grid where no cell has a neighbor above it."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"intro-state","state":{"grid":[[1,1,1],[1,2,2],[0,1,2]],"r":2,"c":2,"filled":[[0,0],[0,1],[0,2],[1,0],[1,1],[1,2],[2,1],[2,2]],"labels":{"grid":"dp"},"changed":[]}}]}},{"id":"all-zero-edge","kind":"case-probe","chapter":"Edge cases","eyebrow":"Stress the rule","title":"For a grid of all 0s, what area comes back?","workspacePanel":"visualizer","summary":"No cell is a 1.","options":[{"id":"zero","label":"0","rationale":"No 1 cell ever writes a side, so the best side stays at its starting value of 0 and 0 squared is 0.","isCorrect":true},{"id":"one","label":"1","rationale":"A side of 1 needs at least one 1 cell to back a 1x1 square. With only 0s there is no square at all."},{"id":"four","label":"4, the cell count","rationale":"The answer is the area of a solid square of ones. With no ones the area is 0."}],"answer":"0. No 1 cell ever updates the best side, so it stays 0 and the returned area is 0.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"all-zero-state","state":{"grid":[[0,0],[0,0]],"r":0,"c":0,"filled":[],"labels":{"grid":"dp"},"changed":[]}}]}},{"id":"single-row-edge","kind":"case-probe","chapter":"Edge cases","eyebrow":"Stress the rule","title":"A single row like [1,1,0,1]. What is the largest side?","workspacePanel":"visualizer","summary":"With one row, every cell reads 0 for its top and diagonal neighbors.","options":[{"id":"one","label":"1","rationale":"The top and diagonal neighbors are off the grid and count as 0, so each 1 cell takes 1 + min(0, ...) = 1 and no square grows past a single cell.","isCorrect":true},{"id":"two","label":"2","rationale":"A 2x2 square needs two rows. One row of ones is a strip, never a square wider than a single cell."},{"id":"three","label":"3, the count of ones","rationale":"The three 1 cells in the row do not form a square. The row is only one cell tall, so the largest square side is 1."}],"answer":"1. The missing row above forces every top neighbor to 0, so 1 + min(0, ...) = 1 for every 1 cell.","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"single-row-state","state":{"grid":[[1,1,0,1]],"r":0,"c":3,"filled":[[0,0],[0,1],[0,3]],"labels":{"grid":"dp"},"changed":[]}}]}},{"id":"ready-to-code","kind":"info","chapter":"Code","eyebrow":"Get ready to code","title":"Seed the border, then one rule fills the rest","workspacePanel":"visualizer","summary":"Every 1 cell is one more than its smallest of three neighbors.","ctaLabel":"Start coding","body":["Make a table shaped like the grid, padded with a zero border so the top, left, and diagonal reads are always valid, and track the best side seen as you go.","Sweep every cell. For a 1 cell, store one more than the smallest of its three filled neighbors and raise the best side if it grew. At the end, square the best side to get the area."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"ready-state","state":{"grid":[[1,1,1],[1,1,1],[0,1,1]],"r":1,"c":0,"filled":[[0,0],[0,1],[0,2],[1,0]],"labels":{"grid":"dp"},"changed":[]}}]}},{"id":"coding","kind":"coding","source":"coding-checkpoints","chapter":"Code","title":"Build the biggest-square table","eyebrow":"Code the rule","summary":"Now turn the rule into code: build a padded table from both dimensions and start the best side at 0, then sweep every cell, writing 1 + min of the three neighbors at each 1 cell and raising the best side as it grows, and square that best at the end.","workspacePanel":"code"},{"id":"complete","kind":"complete","chapter":"Code","eyebrow":"Take it with you","title":"What to carry forward","workspacePanel":"code","summary":"Each cell holds the side of the biggest solid square ending on it: one more than the smallest of its three neighbors.","body":["A square only grows when all three corners around a cell already back one, so the tightest neighbor sets the limit and a single weak corner pins it back.","The diagonal neighbor catches a hole the two wide neighbors would hide, which is why the recurrence reads all three."],"takeaways":[{"title":"Smallest of three, plus one","body":"dp[r][c] = 1 + min(top, left, top-left) turns the grid into one local rule for the square ending at each cell."},{"title":"Track the best, then square it","body":"The largest square can end anywhere, so keep a running best side over all cells and return best squared as the area."}],"nextAction":"Submit when you are ready. TraceCode will run the final checks against the code you wrote."}],"slidesOrigin":"authored"}}
