Workspace Minimum Path Sum
0d
DSA Problem Sheet

Minimum Path Sum

Travel from the top-left to bottom-right grid cell using right or down moves. The total includes both endpoints. Return the smallest path total. Target gives column count.

EXECUTION LAB

Travel from the top-left to bottom-right grid cell using right or down moves. The total includes both endpoints. Return the smallest path total. Target gives column count.

Input and constraints
  • Target is the number of columns. Values must fill a nonempty rectangle.
  • Use at most 32 integers. Each numeric input is between -1000 and 1000.

Code inspector

def solve(values, target):
dp = values.copy()
i = 1
while (i < len(dp)):
if (i < target):
dp[i] = (dp[i] + dp[(i - 1)])
else:
if ((i % target) == 0):
dp[i] = (dp[i] + dp[(i - target)])
else:
dp[i] = (dp[i] + min(dp[(i - target)], dp[(i - 1)]))
i = (i + 1)
return dp[(len(dp) - 1)]

Visualizer

Step 1 of 6
Matrix state
14 •1
213

The first row can only be reached from the left

The first row can only be reached from the left.

Variable watch

i 1

Step explanation

The first row can only be reached from the left.

comparisons 2reads 0writes 0swaps 0recursiveCalls 0
Educational simulation · O(rows × columns) time · O(rows × columns) space

Worked explanation

A courier records the cheapest arrival fare at every junction before moving onward.

Guided solution

Accumulate the cheapest known predecessor at every cell; the first row and column each have only one predecessor.

O(rows × columns) time · O(rows × columns) auxiliary space

Examples

Worked example · {"values":[1,4,1,2,1,3],"target":3} ⇒ 7

Edge case 1 · {"values":[-4],"target":1} ⇒ -4

Edge case 2 · {"values":[2,3],"target":1} ⇒ 5

Progressive hints

Hint 1A courier records the cheapest arrival fare at every junction before moving onward.
Hint 2Accumulate the cheapest known predecessor at every cell; the first row and column each have only one predecessor.
Hint 3Step through the worked example and inspect the highlighted variables before each update.

Common mistake

The start cell must be counted exactly once.

Interview follow-up

How could a second table recover the chosen route?