← Uber bank

Uber · Question 63 · Dynamic Programming

Minimum Path Sum

Dynamic ProgrammingPythoncode⏱ O(m×n)💾 O(1)
Product-based

Problem

Given an m x n grid filled with non-negative numbers, find a path from top-left to bottom-right minimizing the sum (only right/down moves).

Approach

DP grid: dp[i][j] = grid[i][j] + min(dp[i - 1][j], dp[i][j - 1])

Time O(m×n)Space O(1)

How it works

  1. 1Each cell accumulates the cheaper of top/left.
  2. 2First row/column only have one predecessor.
  3. 3Bottom-right holds the minimum total.

Sample input / output

Input:
3 3
1 3 1
1 5 1
4 2 1
Output:
7

Constraints

m == grid.length; 1 <= m, n <= 200; 0 <= grid[i][j] <= 200.

Solution — read it, then walk it

Time O(m×n)Space O(1)Loops 2Branches 5Returns 1source · Python
Scroll sideways for wide charts — the view follows the active step.
↻ repeatyesnoyesnoyesno↻ repeatyesnoSTARTgridm, n = len(grid),len(grid[0])for i in range(m)for j in range(n)if i == 0 and j == 0CONTINUEelif i == 0grid[i][j] += grid[i][j -1]elif j == 0grid[i][j] += grid[i -1][j]ELSEgrid[i][j] += min(grid[i -1][j], grid[i][j - 1])RETURN grid[m - 1][n - 1]DEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)m = int(next(it)); n =int(next(it))grid = [[int(next(it)) for_ in range(n)] for _ inrange(m)]print(minPathSum([row[:]for row in grid]))if __name__ =="__main__"main()END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/23

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits