Minimum Falling Path Sum solution explained
Minimum Falling Path Sum asks for the smallest total you can collect walking from the top row of a square grid to the bottom row, taking one cell per row and moving straight down or one column diagonally each step. Fill the grid one row at a time: the cheapest way to reach a cell is its own value plus the cheapest of the up to three cells above it, and the answer is the smallest value in the last row. That is O(n²) time for an n by n grid and O(n) extra space if you keep only the previous row.
By Evin JohnPublished 9 min read
The task in plain words
You get an n by n grid of integers. Pick any cell in the top row, then move down one row at a time. From column c you may land on column c - 1, c or c + 1 in the next row, as long as that column exists. Add up the cells you land on, including the first and the last. Return the smallest total any such walk can reach.
| Grid (rows top to bottom) | Answer | A cheapest walk |
|---|---|---|
| [4, 1, 7], [2, 8, 3], [6, 5, 9] | 8 | 1, then 2 (one column left), then 5 (one column right) |
| [-2, 5], [3, -4] | -6 | -2, then -4 diagonally |
| [7] | 7 | The only cell |
| [1, 2, 3], [4, 5, 6], [7, 8, 9] | 12 | Straight down the first column |
What the interviewer is looking for
This is a warm-up dynamic programming question. The grid is small and the moves are simple, so the interest is in how you get to the recurrence. A good answer names the subproblem out loud (the cheapest walk that ends at a given cell), explains why the rows can be filled top to bottom, handles the two edge columns without reading outside the grid, and then notices that a full table is not needed. Interviewers often follow up with a variant that changes the move rule, so a clean recurrence pays off twice.
Brute force: try every walk
From any cell there are at most three ways down, so a recursive function can return the cheapest walk that starts at a given cell: its own value plus the best of the cells it can step to. Call it for every top-row cell and take the minimum. It is correct and short, and it is the right thing to say first, but the number of walks is roughly n · 3^(n - 1), so in Python it gets painfully slow somewhere around 15 rows.
def min_falling_brute(grid):
n = len(grid)
def cheapest_from(r, c): # cheapest way down if you are standing on (r, c)
if r == n - 1:
return grid[r][c]
below = [cheapest_from(r + 1, cc) for cc in (c - 1, c, c + 1) if 0 <= cc < n]
return grid[r][c] + min(below)
return min(cheapest_from(0, c) for c in range(n))The waste is easy to point at: the cheapest walk down from cell (2, 1) is computed again for every walk above it that passes through (2, 1). Adding a cache keyed by (r, c) fixes that and already gives O(n²). Turning the cache into a table filled in a fixed order gives the version below, which avoids deep recursion as well.
Row-by-row DP
Flip the direction and ask for the cheapest walk that ends at each cell. For the top row that is just the cell. For any lower cell (r, c), the walk must have come from (r - 1, c - 1), (r - 1, c) or (r - 1, c + 1), so its cost is grid[r][c] plus the smallest of those three totals. Each row depends only on the row above, so one list of n numbers carries the whole state.
def min_falling_path_sum(grid):
n = len(grid)
prev = list(grid[0]) # prev[c]: cheapest path that ends at column c of the row above
for r in range(1, n):
cur = [0] * n
for c in range(n):
best = prev[c]
if c > 0:
best = min(best, prev[c - 1])
if c < n - 1:
best = min(best, prev[c + 1])
cur[c] = grid[r][c] + best
prev = cur
return min(prev)On the first sample grid the rows of totals go [4, 1, 7], then [3, 9, 4], then [9, 8, 13]. The middle cell of the second row is 8 plus the smallest of 4, 1 and 7, which is 9. The answer is the smallest number in the last row, 8, and following the choices back gives the walk 1, 2, 5.
function minFallingPathSum(grid) {
const n = grid.length;
let prev = grid[0].slice();
for (let r = 1; r < n; r++) {
const cur = new Array(n);
for (let c = 0; c < n; c++) {
let best = prev[c];
if (c > 0) best = Math.min(best, prev[c - 1]);
if (c < n - 1) best = Math.min(best, prev[c + 1]);
cur[c] = grid[r][c] + best;
}
prev = cur;
}
return prev.reduce((a, b) => Math.min(a, b));
}Writing a new row each time keeps the old values intact while the current row is being filled. Updating a single array in place is a classic slip: by the time you reach column c, column c - 1 already holds the new row's value, and the result is quietly wrong. If you want to avoid allocating, overwrite the input grid row by row instead, and say that you are changing it.
Cost comparison
| Approach | Time | Extra space |
|---|---|---|
| Plain recursion | About O(n · 3^n) | O(n) call depth |
| Recursion with a cache | O(n²) | O(n²) cache plus O(n) depth |
| Row-by-row table | O(n²) | O(n) with one previous row |
Follow-up: a different column in every row
A common second part changes the move rule: from row to row you may jump to any column except the one you are in. The naive recurrence now looks at n - 1 cells above each cell, which is O(n³) overall. The trick is that each cell only needs the smallest total in the previous row, unless that smallest total sits in its own column, in which case it needs the second smallest. Find both once per row and every cell is O(1) again.
def min_falling_path_sum_shifted(grid):
prev = list(grid[0])
for row in grid[1:]:
low_col = min(range(len(prev)), key=prev.__getitem__) # column of the smallest total
second = min(v for c, v in enumerate(prev) if c != low_col)
prev = [v + (second if c == low_col else prev[low_col]) for c, v in enumerate(row)]
return min(prev)On the grid [1, 2, 3], [4, 5, 6], [7, 8, 9] the original rule allows straight down the first column for 12. The shifted rule forbids that and the answer becomes 13, for example 1, then 5, then 7. Running both on the same grid is a quick way to show the interviewer you understood what changed.
Edge cases worth testing
- A 1 by 1 grid: the answer is the single value.
- All negative values: the minimum must start from real totals, never from a default of 0.
- A cheapest walk that zigzags, so a greedy pick of the smallest cell in each row fails.
- Ties between columns in a row, which should not change the total.
- The two edge columns, which have only two cells above them.
Greedy deserves a word because candidates reach for it. In the grid [1, 9, 2], [9, 9, 1], [9, 9, 1], picking the smallest top cell (the 1 on the left) leaves you far from the cheap right column, and no walk from there costs less than 11. Starting at the 2 instead gives 2 + 1 + 1 = 4. A concrete counterexample like that ends the greedy discussion quickly.
Mistakes that show up a lot
- Reading prev[c - 1] or prev[c + 1] without checking the edges: in Python prev[-1] quietly wraps to the last column, and in JavaScript an index past the end gives undefined, which turns the sum into NaN.
- Updating one array in place, so later columns read this row's values instead of the previous row's.
- Starting the running minimum at 0, which breaks grids where every total is negative.
- Returning the last row's value in a fixed column instead of the minimum over the whole row.
- Treating it as a shortest-path problem and reaching for Dijkstra, which is heavier than needed and fails with negative cells.
Saying it out loud
Fictional example
- Candidate
- Let me define best of r, c as the cheapest walk from the top that ends at row r, column c. The top row is just the grid.
- Candidate
- Any other cell is entered from one of up to three cells directly above, so best of r, c is the cell's value plus the smallest of those three.
- Interviewer
- How much memory does that need?
- Candidate
- Each row only reads the row above, so I keep one list of n totals and build a fresh list per row. That's O(n) extra, O(n squared) time, and the answer is the minimum of the last list.
Problems that use the same idea
Dungeon Game is grid DP too, but it only works when filled from the bottom-right corner backwards, which makes a useful contrast. Delete and Earn keeps two running numbers instead of a row, and Longest Increasing Path in a Matrix needs a memoized search because its moves have no fixed direction. When the moves are free in all four directions and the cost is the highest cell, see Swim in Rising Water.
Practising it with Natively
Grid DP is easy to code and easy to explain badly, so it is a good one to rehearse aloud. In a practice session, Natively on Mac or Windows can read the grid problem from a screenshot and suggest an approach with code in its overlay, which you can check against the recurrence you wrote yourself. If you run a spoken mock round, the transcript it keeps shows whether you actually stated the subproblem before writing code. More on the AI interview assistant.
Questions people ask
How do you solve Minimum Falling Path Sum?
Compute, row by row, the cheapest walk that ends at each cell: the cell's value plus the smallest total among the up to three cells above it. The answer is the minimum of the last row.
What is the time complexity of Minimum Falling Path Sum?
O(n²) for an n by n grid, since each cell looks at three cells above it. Extra space is O(n) if you keep only the previous row.
Why does greedy fail for Minimum Falling Path Sum?
The smallest cell in the top row can sit far from the cheap cells lower down. A walk that starts on a bigger value can still finish with a smaller total.
How do you solve the version where each row must use a different column?
For each row, find the smallest and second smallest totals of the row above. A cell adds the smallest unless that one is in its own column, in which case it adds the second smallest.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
