Home › Company-wise questions › Microsoft › Minimum Path Sum ← Microsoft bank
Microsoft · Question 58 · Dynamic Programming
Minimum Path Sum Dynamic Programming Java code ⏱ O(m×n) 💾 O(1)
Product-based Published and maintained by DSA-topics · Last updated 30 November 2026 · Report an error
About this bank These are classic technical-interview concepts compiled from publicly circulated company-wise question sets, rewritten with original explanations and compiler-ready solutions for educational practice; inclusion does not imply endorsement by the company. Spotted an error? Tell us .
Problem Find the minimum sum path from top-left to bottom-right in a grid.
Approach Accumulate cheapest top/left costs in place.
Time O(m×n)Space O(1)
How it works 1 Seed the first row and column cumulatively. 2 Each cell adds the cheaper of top/left. Sample input / output Input:
3 3
1 3 1
1 5 1
4 2 1
Output:
7 Constraints 1 <= m, n <= 200; 0 <= grid[i][j] <= 200.
Solution — read it, then walk it Flowchart Pseudocode
Time O(m×n)Space O(1)Loops 5Returns 1source · Java
Scroll sideways for wide charts — the view follows the active step. ⤢ Expand
↻ repeat ↻ repeat ↻ repeat ↻ repeat START import java.util.* DEFINE class Main DEFINE static int minPathSum(int[][] grid) DEFINE m = grid.length, n = grid[0].length for (int i = 1; i < m; i++) grid[i][0] += grid[i - 1][0] for (int j = 1; j < n; j++) grid[0][j] += grid[0][j - 1] for (int i = 1; i < m; i++) for (int j = 1; j < n; j++) grid[i][j] += Math.min(grid[i - 1][j], grid[i][j - 1]) RETURN grid[m - 1][n - 1] DEFINE static void main(String[] args) java.util.Scanner sc = new java.util.Scanner(System.in) DEFINE m = sc.nextInt(); int n = sc.nextInt() DEFINE [][] grid = new int[m][n] for (int i = 0; i < m; i++) for (int j = 0; j < n; j++) grid[i][j] … System.out.println(minPathSum(grid)) END start / end statement condition loop returns definition← Q57 · Climbing Stairs Q59 · Longest Increasing Subsequence → Solution code Core logic highlighted in green
Language Python Javasource C++ C Core logic Full code Copy
Recommended resources Affiliate links · may earn us a commission
Classic DSA interview books The reference books interviewers themselves learned from — great next to the visualizers. See the books → Structured coding courses Video courses that pair well with visual practice — pick one language and go deep. Browse courses → Cloud hosting for side projects Ship the portfolio project that gets you hired — free credits for new accounts. Claim credits →