Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Path with smallest sum in JavaScript
This problem involves finding the path through a 2D array that picks exactly one element from each row, where no two adjacent rows can have elements from the same column, and the path has the minimum sum.
Problem Statement
Given a 2D array, we need to:
- Pick exactly one element from each row
- No two elements from adjacent rows can be in the same column
- Return the minimum sum among all valid paths
For example, with the input:
const arr = [
[4, 7, 1],
[2, 8, 3],
[5, 6, 9]
];
Valid Paths Analysis
All valid paths and their sums are:
| Path | Sum | Path | Sum |
|---|---|---|---|
| [4, 8, 9] | 21 | [4, 8, 6] | 18 |
| [4, 3, 6] | 13 | [4, 3, 5] | 12 |
| [7, 2, 6] | 15 | [7, 2, 9] | 18 |
| [7, 3, 6] | 16 | [7, 3, 5] | 15 |
| [1, 2, 6] | 9 | [1, 2, 9] | 12 |
| [1, 8, 9] | 18 | [1, 8, 5] | 14 |
The path [1, 2, 6] has the minimum sum of 9.
Dynamic Programming Solution
The solution uses dynamic programming, working from bottom to top and maintaining the two best options at each level:
const arr = [
[4, 7, 1],
[2, 8, 3],
[5, 6, 9]
];
const minimumPathSum = (arr = []) => {
let first = [0, null]; // [sum, column] of best option
let second = [0, null]; // [sum, column] of second best option
// Process from bottom row to top
for(let row = arr.length - 1; row >= 0; row--) {
let curr1 = null;
let curr2 = null;
// Try each column in current row
for(let column = 0; column < arr[row].length; column++) {
let currentSum = arr[row][column];
// Add best compatible sum from previous row
if(column !== first[1]) {
currentSum += first[0];
} else {
currentSum += second[0];
}
// Update best and second best options
if(curr1 === null || currentSum < curr1[0]) {
curr2 = curr1;
curr1 = [currentSum, column];
} else if(curr2 === null || currentSum < curr2[0]) {
curr2 = [currentSum, column];
}
}
first = curr1;
second = curr2;
}
return first[0];
};
console.log(minimumPathSum(arr));
9
How It Works
The algorithm maintains two variables:
- first: The minimum sum and its column index
- second: The second minimum sum and its column index
For each row, it calculates the minimum sum by adding the current element to either the first or second option from the previous row, ensuring no column conflicts.
Time and Space Complexity
Time Complexity: O(n × m) where n is the number of rows and m is the number of columns.
Space Complexity: O(1) as we only use constant extra space.
Conclusion
This dynamic programming approach efficiently finds the minimum path sum by working bottom-up and maintaining the two best options at each level. The algorithm ensures valid paths while optimizing for the minimum sum.
