Solving with DP

State, transition and borders Β· Part of Strategies

Key idea

Practice

6 questions Β· about 3 min

Explained step by step

Dynamic programming

To recognize a dynamic programming problem, first ask whether it could be solved with backtracking: if the solution comes from a sequence of decisions, it fits a decision tree. There are clues in favor: that it asks for an optimum (the largest, the smallest, the fewest steps) and that the states fit in a list or matrix. And clues against: that it asks for every solution, or for specific permutations or combinations.

Solving a dynamic programming problem usually takes 3 steps. First, see what is decided at each step and define the state and the dp table. Second, find the optimal substructure and write the state transition equation. Third, set the boundary conditions and the order in which the table is filled. With that you can write the code directly, although it is often more natural to go through brute force and memoization first.

The example is the minimum path sum: an n Γ— m grid with a cost in each cell, and a robot that goes from the top left to the bottom right, moving only down or right. At each step it decides down or right, so the state needs 2 variables: the row and the column, [i, j]. dp[i, j] is the minimum sum from [0, 0] to [i, j], and the dp table is the same size as the grid.

Cells in row 0 can only be reached from the left, and cells in column 0 only from above: those are the boundary conditions. With the grid [[1, 3, 1], [1, 5, 1], [4, 2, 1]], row 0 becomes 1, 4, 5 and column 0 becomes 1, 2, 6. Since each cell depends on the one above and the one to the left, it is walked with 2 for loops: the outer one over rows and the inner one over columns. That way, every value needed is already computed.

State transition equation

Cell [i, j] can only be reached from the one above, [i βˆ’ 1, j], or the one to the left, [i, j βˆ’ 1]. The minimum sum to [i, j] uses the smaller of those 2: dp[i, j] = min(dp[i βˆ’ 1, j], dp[i, j βˆ’ 1]) + grid[i, j]. With the grid [[1, 3, 1], [1, 5, 1], [4, 2, 1]]: dp[1, 1] = min(4, 2) + 5 = 7, and the final answer, dp[2, 2], is 7.

Memoization

The grid can be solved in 3 ways. Brute force: from [i, j] go down to [i βˆ’ 1, j] and [i, j βˆ’ 1]; if an index is negative, return infinity. It costs O(2^(n + m)), because many paths reach the same cell. With memoization, each cell is solved once: O(nm). With dynamic programming, also O(nm) time and memory. And since each row only uses the previous one, a single row can be kept: O(m) memory.

Terms in this lesson

Arki, the beaver mascot

Your next interview starts with 5 minutes today.

Free on iOS and Android. Start from zero, no account needed.

Key idea

State, transition and borders