WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Dynamic Programming · Intermediate · question 36 of 100

Solve the Minimum Cost Path problem in a grid using dynamic programming.?

📕 Buy this interview preparation book: 100 Dynamic Programming questions & answers — PDF + EPUB for $5

The Minimum Cost Path problem is a classic dynamic programming problem that involves finding the lowest cost path from the top-left corner of a grid to the bottom-right corner, while moving only down, right, and diagonally down-right.

To solve this problem using dynamic programming, we can create a grid of memoized values, where each cell represents the minimum cost to reach that cell from the top-left corner. We start by initializing the first row and first column with their cumulative values, since there is only one possible path to each cell in these lines.

Then, for each cell in the remaining part of the grid, we calculate the minimum cost to reach that cell by taking the minimum of the three neighboring cells: the cell above, the cell to the left, and the cell diagonally up and left. We add the cost of the current cell to the minimum of these three values to get the minimum cost path to that cell.

Finally, we return the memoized value in the bottom-right corner of the grid, which represents the minimum cost path to reach that point.

Here is an implementation of the Minimum Cost Path problem in Java:

public static int minCostPath(int[][] grid) {
    int m = grid.length;
    int n = grid[0].length;
    int[][] memo = new int[m][n];
    
    // initialize first row and first column
    memo[0][0] = grid[0][0];
    for (int i = 1; i < m; i++) {
        memo[i][0] = memo[i-1][0] + grid[i][0];
    }
    for (int j = 1; j < n; j++) {
        memo[0][j] = memo[0][j-1] + grid[0][j];
    }
    
    // fill in rest of memoized grid
    for (int i = 1; i < m; i++) {
        for (int j = 1; j < n; j++) {
            memo[i][j] = grid[i][j] + Math.min(memo[i-1][j-1], Math.min(memo[i-1][j], memo[i][j-1]));
        }
    }
    
    // return bottom-right corner value
    return memo[m-1][n-1];
}

For example, if we have the following grid:

int[][] grid = {
    {1, 3, 5, 8},
    {4, 2, 1, 7},
    {4, 3, 2, 3}
};

The minimum cost path to reach the bottom-right corner is:

1 -> 3 -> 1 -> 2 -> 3

With a total cost of 8, which is returned by the ‘minCostPath‘ method.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Dynamic Programming interview — then scores it.
📞 Practice Dynamic Programming — free 15 min
📕 Buy this interview preparation book: 100 Dynamic Programming questions & answers — PDF + EPUB for $5

All 100 Dynamic Programming questions · All topics