Python coding

Cheapest path down a triangle

A triangle of integers is given as rows, where row i holds i + 1 numbers. A path starts at the single number on top and moves down one row at a time, from position j to position j or j + 1 of the next row, until it reaches the bottom row. Return the smallest sum that a path can have.

The triangle has 1 to 200 rows, with values between −10,000 and 10,000. Aim for O(n) extra space, where n is the number of rows.

Besides the tests, one large input (a triangle of 23 rows) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • cheapest_path([[1],[2,3],[9,9,1],[9,9,9,1]]) → 6
  • cheapest_path([[4],[1,6],[7,2,5]]) → 7
  • cheapest_path([[-3]]) → -3
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Taking the smaller of the two numbers below at each step fails: a cheap step can lead into an expensive part of the triangle. Use dynamic programming, deciding from the bottom up.

Hint 2

Let best[j] be the cheapest path from position j of a row to the bottom. Start with the bottom row and move up: best[j] = row[j] + min(best[j], best[j + 1]).

Solution and why it works
pythonO(n²), n = rows · O(n)
def cheapest_path(rows: list[list[int]]) -> int:
    best = list(rows[-1])                # best[j]: cheapest path from position j of the current row down
    for row in reversed(rows[:-1]):      # bottom-up, so both children are already solved
        for j, value in enumerate(row):
            best[j] = value + min(best[j], best[j + 1])   # best[j + 1] still holds the row below
    return best[0]

The cheapest path from a number is that number plus the cheaper of the cheapest paths from its two children. Each child is shared by two parents, so solving it once turns 2ⁿ⁻¹ paths into ~n²/2 cells of O(1) work. Going bottom-up leaves the answer at the top and needs a single row. The trap is greedy: picking the smaller child at each step costs 21 on the first example, where 6 is possible.

Related lab: Big-O growth