Dynamic programming

Solve each thing only once · Part of Strategies

Key idea

Practice

6 questions · about 3 min

Explained step by step

Dynamic programming

A staircase has n stairs and each move climbs 1 or 2. In how many ways can you reach the top? Stair i can only be reached from i − 1 or from i − 2, so the ways to reach i are the ways to reach i − 1 plus the ways to reach i − 2: dp[i] = dp[i − 1] + dp[i − 2]. We know dp[1] = 1 and dp[2] = 2. So dp[3] = 3, dp[4] = 5 and dp[5] = 8.

Memoized search goes from the top down. Dynamic programming goes the other way, from the bottom up: it starts with the smallest subproblems, dp[1] and dp[2], and with a for loop computes dp[3], dp[4]... up to dp[n]. No recursion or going back is needed. A list dp stores the solutions, just like mem. The time is O(n) and so is the memory.

dp[i] depends only on dp[i − 1] and dp[i − 2], so there is no need to keep the whole list: 2 variables that keep shifting forward are enough. That lowers the memory from O(n) to O(1). It is called rolling variables or a rolling array. In dynamic programming it is common: if a state depends on a few earlier states, only those are kept.

Recursion tree

The formula gives a brute-force search: start at dp[n] and split it into dp[n − 1] + dp[n − 2], until reaching dp[1] and dp[2]. The recursion tree has depth n and the time is O(2ⁿ). The problem is overlapping subproblems: dp[9] splits into dp[8] and dp[7], and dp[8] into dp[7] and dp[6]. dp[7] is computed 2 times, and the same happens further down, more and more.

Memoization

To solve each subproblem only once, each result is stored in a list mem. The first time dp[i] is computed, it is stored in mem[i]. When it is needed again, it is read from mem[i] instead of recomputed. This memoized search lowers the time from O(2ⁿ) to O(n): with n = 40, from hundreds of millions of calls to about 80. It works from the top down: it starts at dp[n] and goes down.

State transition equation

There are 3 key words. The dp table is the list dp: dp[i] holds the solution to the subproblem for state i. The initial states are those of the smallest subproblems, in stair climbing dp[1] and dp[2]. And the state transition equation is the formula that links a state with the previous ones, dp[i] = dp[i − 1] + dp[i − 2]. In stair climbing, the state is the stair number.

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

Solve each thing only once