Data Structures & AlgorithmsModerateInfosys SP/DSE · Product Company SDE

Problem: Minimum path sum from the top of a number triangle to the bottom (step to the same index or index + 1 in the next row), computed bottom-up.

Problem: Minimum path sum from the top of a number triangle to the bottom (step to the same index or index + 1 in the next row), computed bottom-up.
def tri(t):
    dp = t[-1][:]
    for row in reversed(t[:-1]):
        dp = [x + min(dp[i], dp[i + 1]) for i, x in enumerate(row)]
    return dp[0]
print(tri([[5], [9, 6], [4, 6, 8], [0, 7, 9, 5]]))
What is printed?
  1. A. 18
  2. B. 24
  3. C. 20
  4. D. 16

Correct answer: A. 18

Bottom-up, each cell becomes its value plus the better of its two children: row 2 → 4, 13, 13; row 1 → 9 + 4 = 13, 6 + 13 = 19; top → 5 + 13 = 18 (path 5, 9, 4, 0). Greedy top-down picks 6 over 9 and ends with 5 + 6 + 6 + 7 = 24. O(n²) time, O(n) space.

More Coding Interview Problems questions

Exams that ask this topic