{"id":"minimum-path-sum","title":"Minimum Path Sum","difficulty":"medium","patterns":["dp-2d"],"primaryConcept":"dp-2d-grid","concepts":["dp-2d-grid"],"problemForm":"core","companies":[],"category":"dynamic-programming","compareMode":"exact","syntheticTestConfig":{"inputShape":"matrix","primaryParam":"grid","sizeMetric":"matrix-cells","constraints":["non-negative"]},"description":"Given an m by n grid of non-negative integers, find the minimum sum of a path from the top-left cell to the bottom-right cell when each move can only go right or down.","examples":[{"input":"grid = [[1,3,1],[1,5,1],[4,2,1]]","output":"7","explanation":"The path 1 -> 3 -> 1 -> 1 -> 1 has the minimum sum."},{"input":"grid = [[1,2,3],[4,5,6]]","output":"12","explanation":"The cheapest path is 1 -> 2 -> 3 -> 6."},{"input":"grid = [[5]]","output":"5","explanation":"The start is already the destination."}],"constraints":[{"id":"1-m-n-200","text":"1 <= m, n <= 200","check":[{"kind":"sizeRange","target":"grid","measure":"matrixRows","min":1,"max":200},{"kind":"valueRange","target":"grid","selector":"arrayItemLengths","min":1,"max":200}]},{"id":"0-grid-i-j-200","text":"0 <= grid[i][j] <= 200","check":{"kind":"valueRange","target":"grid","selector":"nestedArrayItems","min":0,"max":200}},{"id":"only-right-and-down-moves-are-allowed","text":"Only right and down moves are allowed"}],"starterCode":"class Solution:\n    def minPathSum(self, grid: list[list[int]]) -> int:\n        # Your code here\n        pass","functionName":"minPathSum","testCases":[{"id":"1","input":{"grid":[[1,3,1],[1,5,1],[4,2,1]]},"expected":7,"description":"Canonical 3x3 grid."},{"id":"2","input":{"grid":[[1,2,3],[4,5,6]]},"expected":12,"description":"Rectangular grid."},{"id":"3","input":{"grid":[[5]]},"expected":5,"description":"Single cell."},{"id":"4","input":{"grid":[[1,2,5]]},"expected":8,"description":"Single row."},{"id":"5","input":{"grid":[[1],[2],[3]]},"expected":6,"description":"Single column."},{"id":"h1","input":{"grid":[[1,2],[1,1]]},"expected":3},{"id":"h2","input":{"grid":[[1],[2],[1]]},"expected":4},{"id":"h3","input":{"grid":[[1,2,3,4]]},"expected":10},{"id":"h4","input":{"grid":[[0,1],[1,0]]},"expected":1},{"id":"h5","input":{"grid":[[5,1,2],[4,8,2],[1,1,1]]},"expected":11},{"id":"topup-single-row","input":{"grid":[[5,1,2,3]]},"expected":11,"description":"Single-row grid has only one route."},{"id":"topup-obstacle-like-expensive-cell","input":{"grid":[[1,9,1],[1,9,1],[1,1,1]]},"expected":5,"description":"The minimum path detours around expensive cells."}],"hints":[{"level":1,"content":"Each cell only depends on the cheapest path into the cell above it or the cell to its left.","revealPattern":false},{"level":2,"content":"Seed the first row and first column before filling the interior cells.","revealPattern":true},{"level":3,"content":"For an interior cell, use `grid[row][col] + min(dp[row - 1][col], dp[row][col - 1])`.","revealPattern":true}],"guidedFlow":{"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":"enumerate-paths","name":"Enumerate every path","summary":"Total every right/down route from start to finish and keep the smallest.","decisionReason":"A 10 by 10 grid already has 48,620 routes, and the count at least triples with each step up in size, so the work explodes with the grid.","complexity":{"time":"O(2^(m+n))","space":"O(m+n)"},"tradeoffs":["Runs in O(2^(m+n)) time and uses O(m+n) space."],"isOptimal":false},{"id":"memoize-paths","name":"Memoized recursion","summary":"Ask each cell for its smallest total recursively, and store every result under the cell's coordinates so it is computed once.","decisionReason":"It also solves each of the m*n cells once, so it reaches O(m*n) time. Filling the table with loops gets the same totals without a recursion stack.","complexity":{"time":"O(m*n)","space":"O(m*n)"},"tradeoffs":["Runs in O(m*n) time, with an O(m*n) cache and an O(m+n) recursion stack."],"isViable":true,"isOptimal":false},{"id":"dp-grid-table","name":"Bottom-up grid table","summary":"Keep one table slot for every grid cell and fill all m*n slots row by row.","decisionReason":"Each of the m*n cells is filled once from the cell above and the cell on its left, in an order that always has both ready.","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":"get-dimensions","title":"Count the rows and the columns","description":"Read how many rows the grid has and how many columns, so the table can be made the same shape.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"reads_grid_input_dimensions","scope":"get-dimensions","readMode":"dp-value-query-v1"}]},"commonMistakes":["Using the row count for both, which only works when the grid is square"],"hint":"The row count is the number of rows in the grid. The column count is the length of any one row.","semanticSpec":{"intent":"Read both dimensions from the input grid.","doneWhen":"This step is done when the implementation derives row and column counts from the grid.","shouldFailWhen":"This step should fail if the code assumes a square grid or never reads one dimension.","roles":["grid","row count","column count"],"mustProve":["The grid row count is read.","The grid column count is read."],"mustNotAccept":["Hard-coded dimensions."]}},{"id":"create-dp-table","title":"Make the table","description":"Create a table with one slot for every grid cell: the same number of rows and the same number of columns.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"initializes_grid_dp_table","scope":"create-dp-table","readMode":"dp-value-query-v1","expected":{"firstAxisInputState":"grid","secondAxisInputState":"grid","firstAxisOffset":0,"secondAxisOffset":0}}]},"commonMistakes":["Building every row of the table from one shared row, so a write to one row shows up in all of them","Making a single row of slots when the grid has several rows"],"hint":"Every cell gets its own total, so the table needs a slot for each one.","semanticSpec":{"intent":"Initialize indexed state with the same shape as the grid.","doneWhen":"This step is done when a two-dimensional DP table is initialized for grid cells.","shouldFailWhen":"This step should fail if no indexed state exists for the grid cells.","roles":["grid","dp table"],"mustProve":["A two-dimensional state table is initialized."],"mustNotAccept":["A scalar-only tracker without cell state."]}},{"id":"base-cases","title":"Fill the start, the first row and the first column","description":"The start cell's total is its own cost. Every other cell in the first row and the first column has one way in, so its total is the total before it plus its own cost.","validation":{"type":"semantic","validator":"all","params":[{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"seeds_grid_origin_cell","scope":"base-cases","readMode":"dp-value-query-v1"}]},{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"seeds_first_axis_border_recurrence","scope":"base-cases","readMode":"dp-value-query-v1"}]},{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"seeds_second_axis_border_recurrence","scope":"base-cases","readMode":"dp-value-query-v1"}]}]},"commonMistakes":["Filling the first row but not the first column, so the cells beside the first column read totals that were never computed","Writing each border cell's own cost without adding the total before it"],"hint":"Along the first row, the total before a cell is the one on its left. Down the first column, it is the one above.","semanticSpec":{"intent":"Seed both grid borders by carrying the adjacent border predecessor plus the current cell cost.","doneWhen":"The first row and first column are filled with cumulative adjacent-border recurrences before the interior scan.","shouldFailWhen":"One border is unseeded or a border cell is written without using its adjacent border predecessor.","roles":["grid DP table","first-row border","first-column border"],"mustProve":["first-axis border recurrence","second-axis border recurrence"],"mustNotAccept":["constant-only border seeding"],"proofSnippets":[{"id":"py-seed-border-paths","language":"python","code":"class Solution:\n    def minPathSum(self, grid):\n        m = len(grid)\n        n = len(grid[0])\n        dp = [[0] * n for _ in range(m)]\n        dp[0][0] = grid[0][0]\n        for col in range(1, n):\n            dp[0][col] = dp[0][col - 1] + grid[0][col]\n        for row in range(1, m):\n            dp[row][0] = dp[row - 1][0] + grid[row][0]"}]}},{"id":"nested-loops","title":"Fill every other cell","description":"Visit the remaining cells row by row. Each one takes its own cost plus the smaller of two totals: the cell above it and the cell on its left.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"loops_over_interior_grid","scope":"nested-loops","readMode":"dp-value-query-v1"}]},"commonMistakes":["Starting at the first row or first column, where the cell above or the cell on the left does not exist","Comparing the two neighbors' own costs from the grid instead of their totals from the table"],"hint":"Start at the second row and the second column. The first row and first column are already filled.","semanticSpec":{"intent":"Iterate over the grid interior after borders are seeded.","doneWhen":"This step is done when nested loops visit non-border grid cells.","shouldFailWhen":"This step should fail if the implementation never scans the two-dimensional interior.","roles":["row index","column index","interior cell"],"mustProve":["Nested loops scan the interior cell coordinates."],"mustNotAccept":["Only seeding border cells."]}},{"id":"return-answer","title":"Return the bottom-right cell","description":"Return the total stored for the finish: the last row, last column of the table.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"returns_bottom_right_cell","scope":"return-answer","readMode":"dp-value-query-v1"}]},"commonMistakes":["Returning the bottom-right value of the grid, which is only that cell's own cost"],"hint":"That cell holds the smallest total of any route from the start to the finish.","semanticSpec":{"intent":"Return the terminal grid state for the destination.","doneWhen":"This step is done when the solution returns the bottom-right DP cell.","shouldFailWhen":"This step should fail if the code returns another cell or the full table.","roles":["dp table","destination cell"],"mustProve":["The terminal return reads the bottom-right indexed state."],"mustNotAccept":["Returning an intermediate row or column state."]}}],"version":2,"slides":[{"id":"read-the-signal","kind":"info","title":"The cheapest route across a grid of costs","workspacePanel":"problem","body":["Every cell of the grid holds a cost. A route starts on the top-left cell and ends on the bottom-right cell, and each move goes one cell to the right or one cell down.","A route's total is the sum of the costs of the cells it stands on, with the start and the finish included. Return the smallest total any route can have."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"the-grid","state":{"grid":[[1,4,2],[2,6,1],[3,5,2]]}}]}},{"id":"route-total","kind":"case-probe","title":"One route goes down, right, right, down. What is its total?","workspacePanel":"visualizer","options":[{"id":"twelve","label":"12","rationale":"It stands on 1, 2, 6, 1 and 2. The start and the finish both count.","isCorrect":true},{"id":"eleven","label":"11","rationale":"That leaves out the 1 the route starts on. The start cell is part of every route, so its cost is always paid.","isCorrect":false},{"id":"four","label":"4","rationale":"4 is the number of moves. The total adds up costs, and this route stands on five cells.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"one-route","state":{"grid":[[1,4,2],[2,6,1],[3,5,2]],"filled":[[0,0],[1,0],[1,1],[1,2],[2,2]],"changed":[]}}]}},{"id":"cheaper-step","kind":"case-probe","title":"Suppose a walker always steps onto the cheaper of its two next cells. What total does it finish with?","workspacePanel":"visualizer","options":[{"id":"thirteen","label":"13","rationale":"It goes down to the 2 rather than right to the 4, then down to the 3 rather than right to the 6. On the bottom row it crosses the 5 and the 2: 1 + 2 + 3 + 5 + 2 = 13. The route through the 6 totaled 12, so the cheaper step cannot be trusted.","isCorrect":true},{"id":"twelve","label":"12","rationale":"12 belongs to the down, right, right, down route. The walker leaves that route at its second step, where the 3 below is cheaper than the 6 to the right.","isCorrect":false},{"id":"eight","label":"8","rationale":"1 + 2 + 3 + 2 leaves out the 5. Once the walker is on the bottom row its only move is right, so it has to cross the 5 to reach the finish.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"walker-at-start","state":{"grid":[[1,4,2],[2,6,1],[3,5,2]],"r":0,"c":0}}]}},{"id":"enumerate-cost","kind":"case-probe","title":"Totaling every route and keeping the smallest always works. How many routes cross a 10 by 10 grid?","summary":"Routes by grid size: 2 by 2 has 2, 3 by 3 has 6, 4 by 4 has 20, 5 by 5 has 70.","workspacePanel":"visualizer","options":[{"id":"tens-of-thousands","label":"48,620","rationale":"Each step up in size multiplies the count by 3 or more: 2, 6, 20, 70, then 252, 924, 3,432, 12,870 and 48,620. A grid in this problem can be 200 by 200, and no program can total every route on a grid that size.","isCorrect":true},{"id":"one-per-cell","label":"100","rationale":"100 is the number of cells. The 5 by 5 grid has 25 cells and already has 70 routes.","isCorrect":false},{"id":"ten-times","label":"About 700","rationale":"That is ten times the 5 by 5 count. The count at least triples with each step up in size, and 10 by 10 is five steps past 5 by 5.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"the-grid","state":{"grid":[[1,4,2],[2,6,1],[3,5,2]]}}]}},{"id":"shared-cell","kind":"case-probe","title":"Instead of whole routes, take one cell. Two routes meet on the middle cell with 9 and 11 so far. Can the 11 still end up cheapest?","workspacePanel":"visualizer","options":[{"id":"cannot-win","label":"No: any finish open to the 11 is open to the 9","rationale":"The cells ahead are the same for both. Whatever the 11 does from here, the 9 can do the same and finish 2 lower. So a route that arrives with 11 can be dropped here, without following it to the finish.","isCorrect":true},{"id":"cheaper-cells","label":"Yes, if it picks cheaper cells for the rest of the way","rationale":"There are no cheaper cells for it alone. Both routes stand on the same cell, so the same moves are open to each of them.","isCorrect":false},{"id":"pays-off-later","label":"Yes: its expensive first step can still pay off later","rationale":"An expensive step pays off only by leading somewhere cheaper. These two routes are already in the same place, with the same cells ahead.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"two-arrivals","state":{"grid":[[1,4,2],[2,6,1],[3,5,2]],"r":1,"c":1,"dependsOn":[[0,1],[1,0]]}}]}},{"id":"state-meaning","kind":"case-probe","title":"What one number is worth keeping for each cell?","workspacePanel":"visualizer","options":[{"id":"cheapest-to-cell","label":"The smallest total of any route from the start to that cell","rationale":"Any route that arrives with more can be dropped, the way the 11 was dropped at the middle cell.","isCorrect":true},{"id":"raw-cost","label":"The cell's own cost, as written in the grid","rationale":"The grid already holds that, and it says nothing about getting there: the middle cell costs 6, and routes arrive on it with 9 or 11.","isCorrect":false},{"id":"walker-total","label":"The total the cheaper-step walker has when it gets there","rationale":"The walker never reaches the middle cell. Where it does arrive it can be beaten: it reached the finish with 13, and another route got there with 12.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"the-grid","state":{"grid":[[1,4,2],[2,6,1],[3,5,2]]}}]}},{"id":"approach-selection","kind":"info","title":"One table, the same shape as the grid","workspacePanel":"visualizer","body":["Keep those totals in a table with one slot per grid cell, and call it `dp`. `dp[r][c]` holds the smallest total of any route from the start to the cell in row r, column c.","That total counts the cell itself, so the start gets its own cost, 1. In the drawing, every other cell shows its own cost until its total goes in."],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"start-filled","state":{"grid":[[1,4,2],[2,6,1],[3,5,2]],"filled":[[0,0]],"changed":[],"labels":{"grid":"dp"}}}]}},{"id":"edges-base","kind":"case-probe","title":"What is the smallest total to reach the top-right cell?","workspacePanel":"visualizer","options":[{"id":"seven","label":"7","rationale":"Only one route gets there, straight along the top row: 1 + 4 + 2 = 7. So after the start, each first-row cell is the total on its left plus its own cost, which gives 1, 5, 7. The first column also has one way in, from above, and fills going down: 1, 3, 6.","isCorrect":true},{"id":"own-cost","label":"2","rationale":"2 is the cell's own cost. The route also pays for the 1 and the 4 it crosses on the way.","isCorrect":false},{"id":"rows-below","label":"It cannot be known until the rows below are filled","rationale":"Moves only go right or down, so a route that leaves the top row never comes back to it. No cell in the rows below is on any route to this cell.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"top-right","state":{"grid":[[1,4,2],[2,6,1],[3,5,2]],"filled":[[0,0]],"changed":[],"r":0,"c":2,"labels":{"grid":"dp"}}}]}},{"id":"trace","kind":"dry-run","source":"trace-example","title":"Fill the four cells that are left","workspacePanel":"visualizer","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"borders-filled","state":{"grid":[[1,5,7],[3,6,1],[6,5,2]],"filled":[[0,0],[0,1],[0,2],[1,0],[2,0]],"changed":[],"labels":{"grid":"dp"}}},{"id":"next-cell","state":{"grid":[[1,5,7],[3,6,1],[6,5,2]],"filled":[[0,0],[0,1],[0,2],[1,0],[2,0]],"changed":[],"r":1,"c":1,"dependsOn":[[0,1],[1,0]],"labels":{"grid":"dp"}}},{"id":"middle-cell","state":{"grid":[[1,5,7],[3,9,1],[6,5,2]],"filled":[[0,0],[0,1],[0,2],[1,0],[2,0],[1,1]],"changed":[[1,1]],"r":1,"c":2,"dependsOn":[[0,2],[1,1]],"labels":{"grid":"dp"}}},{"id":"end-of-row","state":{"grid":[[1,5,7],[3,9,8],[6,5,2]],"filled":[[0,0],[0,1],[0,2],[1,0],[2,0],[1,1],[1,2]],"changed":[[1,2]],"r":2,"c":1,"dependsOn":[[1,1],[2,0]],"labels":{"grid":"dp"}}},{"id":"bottom-right","state":{"grid":[[1,5,7],[3,9,8],[6,11,10]],"filled":[[0,0],[0,1],[0,2],[1,0],[1,1],[1,2],[2,0],[2,1],[2,2]],"changed":[[2,1],[2,2]],"labels":{"grid":"dp"}}}]},"beats":[{"id":"next-cell","title":"The first row and first column are filled. Which cell can be filled next?","options":[{"id":"middle","label":"The middle cell","rationale":"Routes enter it from the cell above or the cell on its left, and both already hold their totals. Going row by row, left to right, every remaining cell finds both of those filled.","isCorrect":true},{"id":"bottom-right","label":"The bottom-right cell","rationale":"Routes enter it from the cell above or the cell on its left, and neither of those has a total yet.","isCorrect":false},{"id":"end-of-middle-row","label":"The cell at the end of the middle row","rationale":"The cell above it is filled, but routes also enter it from the middle cell, which has no total yet.","isCorrect":false}]},{"id":"middle-cell","title":"What total goes in the middle cell?","options":[{"id":"left","label":"9: the 3 on its left plus its own 6","rationale":"The cheaper way in is from the left. A route arriving from above would bring 5 instead of 3. These are the same 9 and 11 the two routes brought to this cell earlier.","isCorrect":true},{"id":"above","label":"11: the 5 above it plus its own 6","rationale":"A route can also arrive from the left, with 3 so far. The table keeps the smallest total.","isCorrect":false},{"id":"both","label":"14: both neighbors plus its own 6","rationale":"A route enters through one neighbor. Adding both counts cells that no single route stands on together.","isCorrect":false}]},{"id":"end-of-row","title":"What total goes in the last cell of the middle row?","options":[{"id":"above","label":"8: the 7 above it plus its own 1","rationale":"This time the smaller total is above. Which side is smaller can change from cell to cell, so both are compared every time.","isCorrect":true},{"id":"left","label":"10: the 9 on its left plus its own 1","rationale":"The left side was cheaper at the middle cell. Here the left holds 9 and the cell above holds 7.","isCorrect":false},{"id":"copy","label":"7: the same as the cell above it","rationale":"7 is the total to reach the cell above. Stepping down onto this cell adds its own cost, 1.","isCorrect":false}]},{"id":"bottom-right","title":"The last row fills the same way. What total ends up in the bottom-right cell?","options":[{"id":"ten","label":"10","rationale":"The cell before it takes the 6 on its left: 6 + 5 = 11. The bottom-right cell then has 8 above and 11 on its left, and 8 + 2 = 10. That cell is the finish, so 10 is the value to return.","isCorrect":true},{"id":"thirteen","label":"13","rationale":"13 comes from the left, 11 + 2, but the cell above holds 8, and 8 + 2 is smaller. 13 is the cheaper-step walker's total.","isCorrect":false},{"id":"twelve","label":"12","rationale":"12 is the down, right, right, down route. The table finds a cheaper one: along the top row, then down the last column.","isCorrect":false}]}]},{"id":"edge-case-intro","kind":"info","title":"The table returned 10 for this grid. Next, two smaller grids.","workspacePanel":"visualizer","body":["The first is a single row. The second is a single cell.","This grid had a first row, a first column and four cells between them. Do the same steps still return the right total when some of those parts are missing?"],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"table-full","state":{"grid":[[1,5,7],[3,9,8],[6,11,10]],"filled":[[0,0],[0,1],[0,2],[1,0],[1,1],[1,2],[2,0],[2,1],[2,2]],"changed":[],"labels":{"grid":"dp"}}}]}},{"id":"single-row-edge","kind":"case-probe","title":"The first grid is a single row. What does the function return?","workspacePanel":"visualizer","options":[{"id":"running-total","label":"9","rationale":"The first row fills as 3, 4, 9, and the last cell of that row is the bottom-right cell. There is no first column below the start and no cell with two ways in, so nothing else is written.","isCorrect":true},{"id":"own-cost","label":"5","rationale":"5 is the last cell's own cost. The only route also crosses the 3 and the 1.","isCorrect":false},{"id":"never-filled","label":"Nothing useful: no cell here has both a cell above and a cell on its left","rationale":"Those cells are filled by the first-row step, which needs only the cell on the left. The step for cells with two ways in has nothing to visit.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"single-row","state":{"grid":[[3,1,5]]}}]}},{"id":"single-cell-edge","kind":"case-probe","title":"The second grid is a single cell. What does the function return?","workspacePanel":"visualizer","options":[{"id":"own-cost","label":"6","rationale":"The start is also the finish. Its total is its own cost, and it is the bottom-right cell of the table. Neither grid needed special handling: a step whose part of the grid is missing has no cells to visit.","isCorrect":true},{"id":"zero","label":"0","rationale":"No move is made, but the route still stands on the cell and pays its cost.","isCorrect":false},{"id":"no-route","label":"Nothing: there is no route to take","rationale":"Standing on the start is already a complete route, with total 6.","isCorrect":false}],"visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"single-cell","state":{"grid":[[6]]}}]}},{"id":"ready-to-code","kind":"info","title":"One total per cell, filled from the top-left. Now write the function.","workspacePanel":"visualizer","body":["The function makes a table the same shape as the grid.","The start cell gets its own cost. Along the rest of the first row, each cell adds its cost to the total on its left. Down the rest of the first column, each cell adds its cost to the total above.","Then, row by row and left to right, every remaining cell takes its own cost plus the smaller of the two totals above it and on its left.","The function returns the total in the bottom-right cell."],"ctaLabel":"Start coding","visualTrace":{"contract":"guided-visual-trace-v1","steps":[{"id":"table-full","state":{"grid":[[1,5,7],[3,9,8],[6,11,10]],"filled":[[0,0],[0,1],[0,2],[1,0],[1,1],[1,2],[2,0],[2,1],[2,2]],"changed":[],"labels":{"grid":"dp"}}}]}},{"id":"coding","kind":"coding","source":"coding-checkpoints","title":"Build the table and return its last cell","workspacePanel":"code","checkpoints":[{"id":"get-dimensions","title":"Count the rows and the columns","description":"Read how many rows the grid has and how many columns, so the table can be made the same shape.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"reads_grid_input_dimensions","scope":"get-dimensions","readMode":"dp-value-query-v1"}]},"commonMistakes":["Using the row count for both, which only works when the grid is square"],"hint":"The row count is the number of rows in the grid. The column count is the length of any one row.","semanticSpec":{"intent":"Read both dimensions from the input grid.","doneWhen":"This step is done when the implementation derives row and column counts from the grid.","shouldFailWhen":"This step should fail if the code assumes a square grid or never reads one dimension.","roles":["grid","row count","column count"],"mustProve":["The grid row count is read.","The grid column count is read."],"mustNotAccept":["Hard-coded dimensions."]}},{"id":"create-dp-table","title":"Make the table","description":"Create a table with one slot for every grid cell: the same number of rows and the same number of columns.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"initializes_grid_dp_table","scope":"create-dp-table","readMode":"dp-value-query-v1","expected":{"firstAxisInputState":"grid","secondAxisInputState":"grid","firstAxisOffset":0,"secondAxisOffset":0}}]},"commonMistakes":["Building every row of the table from one shared row, so a write to one row shows up in all of them","Making a single row of slots when the grid has several rows"],"hint":"Every cell gets its own total, so the table needs a slot for each one.","semanticSpec":{"intent":"Initialize indexed state with the same shape as the grid.","doneWhen":"This step is done when a two-dimensional DP table is initialized for grid cells.","shouldFailWhen":"This step should fail if no indexed state exists for the grid cells.","roles":["grid","dp table"],"mustProve":["A two-dimensional state table is initialized."],"mustNotAccept":["A scalar-only tracker without cell state."]}},{"id":"base-cases","title":"Fill the start, the first row and the first column","description":"The start cell's total is its own cost. Every other cell in the first row and the first column has one way in, so its total is the total before it plus its own cost.","validation":{"type":"semantic","validator":"all","params":[{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"seeds_grid_origin_cell","scope":"base-cases","readMode":"dp-value-query-v1"}]},{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"seeds_first_axis_border_recurrence","scope":"base-cases","readMode":"dp-value-query-v1"}]},{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"seeds_second_axis_border_recurrence","scope":"base-cases","readMode":"dp-value-query-v1"}]}]},"commonMistakes":["Filling the first row but not the first column, so the cells beside the first column read totals that were never computed","Writing each border cell's own cost without adding the total before it"],"hint":"Along the first row, the total before a cell is the one on its left. Down the first column, it is the one above.","semanticSpec":{"intent":"Seed both grid borders by carrying the adjacent border predecessor plus the current cell cost.","doneWhen":"The first row and first column are filled with cumulative adjacent-border recurrences before the interior scan.","shouldFailWhen":"One border is unseeded or a border cell is written without using its adjacent border predecessor.","roles":["grid DP table","first-row border","first-column border"],"mustProve":["first-axis border recurrence","second-axis border recurrence"],"mustNotAccept":["constant-only border seeding"],"proofSnippets":[{"id":"py-seed-border-paths","language":"python","code":"class Solution:\n    def minPathSum(self, grid):\n        m = len(grid)\n        n = len(grid[0])\n        dp = [[0] * n for _ in range(m)]\n        dp[0][0] = grid[0][0]\n        for col in range(1, n):\n            dp[0][col] = dp[0][col - 1] + grid[0][col]\n        for row in range(1, m):\n            dp[row][0] = dp[row - 1][0] + grid[row][0]"}]}},{"id":"nested-loops","title":"Fill every other cell","description":"Visit the remaining cells row by row. Each one takes its own cost plus the smaller of two totals: the cell above it and the cell on its left.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"loops_over_interior_grid","scope":"nested-loops","readMode":"dp-value-query-v1"}]},"commonMistakes":["Starting at the first row or first column, where the cell above or the cell on the left does not exist","Comparing the two neighbors' own costs from the grid instead of their totals from the table"],"hint":"Start at the second row and the second column. The first row and first column are already filled.","semanticSpec":{"intent":"Iterate over the grid interior after borders are seeded.","doneWhen":"This step is done when nested loops visit non-border grid cells.","shouldFailWhen":"This step should fail if the implementation never scans the two-dimensional interior.","roles":["row index","column index","interior cell"],"mustProve":["Nested loops scan the interior cell coordinates."],"mustNotAccept":["Only seeding border cells."]}},{"id":"return-answer","title":"Return the bottom-right cell","description":"Return the total stored for the finish: the last row, last column of the table.","validation":{"type":"semantic","validator":"familyFact","params":[{"family":"dp","fact":"returns_bottom_right_cell","scope":"return-answer","readMode":"dp-value-query-v1"}]},"commonMistakes":["Returning the bottom-right value of the grid, which is only that cell's own cost"],"hint":"That cell holds the smallest total of any route from the start to the finish.","semanticSpec":{"intent":"Return the terminal grid state for the destination.","doneWhen":"This step is done when the solution returns the bottom-right DP cell.","shouldFailWhen":"This step should fail if the code returns another cell or the full table.","roles":["dp table","destination cell"],"mustProve":["The terminal return reads the bottom-right indexed state."],"mustNotAccept":["Returning an intermediate row or column state."]}}]},{"id":"complete","kind":"complete","title":"The smallest total to every cell, one cell at a time","workspacePanel":"code","takeaways":[{"title":"One number per cell is enough","body":"Two routes that meet on a cell have the same cells ahead, so only the smallest total that arrives there needs keeping. Every other route to that cell is dropped without being followed."},{"title":"Above or left, whichever is smaller","body":"`dp[r][c] = grid[r][c] + min(dp[r-1][c], dp[r][c-1])`. After the start, cells in the first row and first column have one way in, so they are running totals."},{"title":"Each cell is filled once","body":"A grid with m rows and n columns has m·n cells, and each is filled once from at most two neighbors, so the time is O(m·n). The table has one slot per cell, so the space is O(m·n) too. Totaling every route would mean 48,620 routes on a 10 by 10 grid alone."}]}],"slidesOrigin":"authored","progressRevision":"minimum-path-sum-2026-11-20-one-grid-rewrite"},"executionStyle":"solution-method"}
