Minimum Path Sum in Grid in DSA Javascript - Time & Space Complexity
We want to know how the time needed to find the minimum path sum in a grid changes as the grid size grows.
How does the number of steps grow when the grid gets bigger?
Analyze the time complexity of the following code snippet.
function minPathSum(grid) {
const m = grid.length;
const n = grid[0].length;
const dp = Array(m).fill(null).map(() => Array(n).fill(0));
dp[0][0] = grid[0][0];
for (let i = 1; i < m; i++) dp[i][0] = dp[i - 1][0] + grid[i][0];
for (let j = 1; j < n; j++) dp[0][j] = dp[0][j - 1] + grid[0][j];
for (let i = 1; i < m; i++) {
for (let j = 1; j < n; j++) {
dp[i][j] = Math.min(dp[i - 1][j], dp[i][j - 1]) + grid[i][j];
}
}
return dp[m - 1][n - 1];
}
This code finds the smallest sum path from the top-left to the bottom-right of a grid, moving only down or right.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Nested loops over the grid cells to fill the dp table.
- How many times: Each cell is visited once, so m x n times.
As the grid size grows, the number of operations grows with the total number of cells.
| Input Size (m x n) | Approx. Operations |
|---|---|
| 10 x 10 | 100 |
| 100 x 100 | 10,000 |
| 1000 x 1000 | 1,000,000 |
Pattern observation: Operations grow proportionally to the number of cells, so doubling rows and columns quadruples work.
Time Complexity: O(m x n)
This means the time needed grows directly with the total number of cells in the grid.
[X] Wrong: "The time complexity is O(m + n) because we only move down or right."
[OK] Correct: Even though moves are down or right, the algorithm must visit every cell to find the minimum path, so it depends on the total number of cells, not just the edges.
Understanding how nested loops over a grid affect time helps you explain and optimize grid-based problems confidently.
What if we allowed moving diagonally as well? How would the time complexity change?
Practice
Given a grid of numbers, find the path from top-left to bottom-right with the smallest sum.Solution
Step 1: Understand the problem goal
The problem asks to find a path from the top-left corner to the bottom-right corner of a grid that has the smallest sum of all numbers along the path.Step 2: Clarify path movement
Movement is only allowed down or right, so the path must be chosen to minimize the total sum.Final Answer:
The path with the smallest sum of numbers from top-left to bottom-right -> Option BQuick Check:
Minimum path sum means smallest total sum [OK]
- Confusing minimum with maximum path sum
- Counting number of paths instead of sum
- Ignoring movement restrictions (only right/down)
dp for dynamic programming with the same size as grid?Solution
Step 1: Understand 2D array initialization
UsingArray.fromwith a mapping function creates independent inner arrays, avoiding shared references.Step 2: Analyze each option
const dp = Array(grid.length).fill(Array(grid[0].length).fill(0)); usesfillwith an array, causing all rows to reference the same array (wrong). const dp = Array.from({ length: grid.length }, () => Array(grid[0].length).fill(0)); correctly creates independent arrays. const dp = new Array(grid.length).fill(new Array(grid[0].length)); fills with undefined arrays (wrong). const dp = Array(grid.length).map(() => Array(grid[0].length).fill(0)); usesmapon an uninitialized array, which returns empty array (wrong).Final Answer:
const dp = Array.from({ length: grid.length }, () => Array(grid[0].length).fill(0)); -> Option AQuick Check:
Use Array.from with function for independent rows [OK]
- Using fill with array causes shared references
- Using map on uninitialized array returns empty
- Not initializing inner arrays properly
const grid = [[1,3,1],[1,5,1],[4,2,1]];
function minPathSum(grid) {
const m = grid.length, n = grid[0].length;
const dp = Array.from({ length: m }, () => Array(n).fill(0));
dp[0][0] = grid[0][0];
for(let i = 1; i < m; i++) dp[i][0] = dp[i-1][0] + grid[i][0];
for(let j = 1; j < n; j++) dp[0][j] = dp[0][j-1] + grid[0][j];
for(let i = 1; i < m; i++) {
for(let j = 1; j < n; j++) {
dp[i][j] = Math.min(dp[i-1][j], dp[i][j-1]) + grid[i][j];
}
}
return dp[m-1][n-1];
}
console.log(minPathSum(grid));Solution
Step 1: Initialize dp with first row and column sums
dp[0][0]=1; dp[1][0]=1+1=2; dp[2][0]=2+4=6; dp[0][1]=1+3=4; dp[0][2]=4+1=5;Step 2: Fill dp for other cells using minimum of top or left
dp[1][1]=min(dp[0][1],dp[1][0])+5=min(4,2)+5=7; dp[1][2]=min(dp[0][2],dp[1][1])+1=min(5,7)+1=6; dp[2][1]=min(dp[1][1],dp[2][0])+2=min(7,6)+2=8; dp[2][2]=min(dp[1][2],dp[2][1])+1=min(6,8)+1=7;Final Answer:
7 -> Option AQuick Check:
Minimum path sum calculated = 7 [OK]
- Adding max instead of min
- Incorrect initialization of dp edges
- Mixing up indices in loops
function minPathSum(grid) {
const m = grid.length, n = grid[0].length;
const dp = Array(m).fill(Array(n).fill(0));
dp[0][0] = grid[0][0];
for(let i = 1; i < m; i++) dp[i][0] = dp[i-1][0] + grid[i][0];
for(let j = 1; j < n; j++) dp[0][j] = dp[0][j-1] + grid[0][j];
for(let i = 1; i < m; i++) {
for(let j = 1; j < n; j++) {
dp[i][j] = Math.min(dp[i-1][j], dp[i][j-1]) + grid[i][j];
}
}
return dp[m-1][n-1];
}Solution
Step 1: Identify the dp initialization problem
UsingArray(m).fill(Array(n).fill(0))causes all rows to reference the same inner array, leading to incorrect updates.Step 2: Fix dp initialization
UseArray.from({ length: m }, () => Array(n).fill(0))to create independent inner arrays for each row.Final Answer:
Replace dp initialization with Array.from to avoid shared references -> Option CQuick Check:
Use Array.from for independent rows in 2D array [OK]
- Using fill with arrays causing shared references
- Changing min to max breaks logic
- Removing dp causes wrong results
[[2,1,3],[6,5,4],[7,8,9]]
What is the minimum path sum if you can only move right or down from the top-left to bottom-right?
Solution
Step 1: Initialize dp edges
dp[0][0]=2; first row: dp[0][1]=2+1=3; dp[0][2]=3+3=6; first column: dp[1][0]=2+6=8; dp[2][0]=8+7=15;Step 2: Fill dp inner cells
dp[1][1]=min(dp[0][1],dp[1][0])+5=min(3,8)+5=8; dp[1][2]=min(dp[0][2],dp[1][1])+4=min(6,8)+4=10; dp[2][1]=min(dp[1][1],dp[2][0])+8=min(8,15)+8=16; dp[2][2]=min(dp[1][2],dp[2][1])+9=min(10,16)+9=19;Step 3: Verify final dp value
The bottom-right dp value is 19, but check if a better path exists by tracing:Step 4: Trace path for minimum sum
Path: 2 -> 1 -> 3 -> 4 -> 9 sums to 19; Path: 2 -> 1 -> 5 -> 4 -> 9 sums to 21; Path: 2 -> 6 -> 5 -> 4 -> 9 sums to 26; Path: 2 -> 6 -> 8 -> 9 sums to 25; So minimum is 19.Final Answer:
19 -> Option DQuick Check:
Minimum path sum calculated = 19 [OK]
- Not initializing first row and column correctly
- Adding max instead of min
- Misreading grid values
Ready to prove it?
Pass the test and this pattern moves unknown
