Data Structures & AlgorithmsEasyTCS NQT Digital · Product Company SDE

Problem: Find the minimum path sum from the top-left to the bottom-right of a cost grid (moves: right or down).

Problem: Find the minimum path sum from the top-left to the bottom-right of a cost grid (moves: right or down).
def minpath(g):
    R, C = len(g), len(g[0])
    for r in range(R):
        for c in range(C):
            if r == 0 and c == 0: continue
            up = g[r-1][c] if r else float('inf')
            left = g[r][c-1] if c else float('inf')
            g[r][c] += min(up, left)
    return g[-1][-1]
print(minpath([[1, 3, 1], [1, 5, 1], [4, 2, 1]]))
What is printed?
  1. A. 8
  2. B. 6
  3. C. 7
  4. D. 11

Correct answer: C. 7

Each cell adds the cheaper of its top and left neighbours. Best route 1 → 3 → 1 → 1 → 1 = 7. A greedy walk that always steps to the cheaper next cell would go down to 1, then right to 5… and pay more. O(R·C), done in place.

More Coding Interview Problems questions

Exams that ask this topic