cswork / templatesOpen the Line 500 list

STOP 22 · DYNAMIC PROGRAMMING

Dynamic Programming Fundamentals and State Design

1-D DP with rolling variables O(n) time · O(1) space

Contest ratings Rating 1358–Rating 1780· median Rating 1569(2 of 10 problems rated by zerotrac)

Open the Line 500 list · stop 22 · 10 problems
Learn first
Leads to
How often asked
asked by 9 companies · in 10 reportsSnap 2, Intuit 1, Microsoft 1, Morgan Stanley 1, Paradromics 1

Warm up with this one

LC 509Fibonacci NumberEasy
Stuck? Peek at the approach

Compare recursion, memoization, and rolling variables to understand repeated subproblems and explain time and space complexity.

Key points

  1. Define the state in one sentence, such as dp[i] = the best answer using the first i elements; once that is precise, the transition usually follows.
  2. Derive the transition from the last decision: take element i or not, last jump of 1 step or 2.
  3. When dp[i] depends only on the previous one or two values, roll two variables and cut space from O(n) to O(1).

Common pitfalls

  • dp and input indexes drift apart: with one extra slot dp[0] means "nothing chosen yet" and the answer is dp[n].
  • When rolling, overwriting prev1 before computing the new value means you read the updated value by mistake.
  • Counts quickly outgrow 64 bits; when the problem asks for a modulus, apply it at every step.

Watch it run

Step through the pattern on a small example. Pause, step forwards or back, or drag the slider to any step.

Interactive demo · step by step

Dynamic programming · coin change

Coins 1, 3, 4, unlimited of each: make 6

Try your own input
0dp[0]
∞dp[1]
∞dp[2]
∞dp[3]
∞dp[4]
∞dp[5]
∞dp[6]
CurrentDiscovered / computedAnswer
Amount
6
Current
—
Fewest coins
not reachable yet

dp[0] = 0 and every other state starts at ∞ (unreachable). dp[x] is the fewest coins that make x.

InvariantAmounts go up one by one; when dp[x] is updated, every smaller amount is already optimal.

Template

Open one language. All four implement the same template, and each one is compiled, run and checked against test data. Then rewrite the warm-up, LC 509, with it.

Python
def rob(nums: list[int]) -> int:
    """Largest sum of elements with no two adjacent."""
    prev2 = prev1 = 0  # best totals up to i-2 and up to i-1
    for x in nums:
        prev2, prev1 = prev1, max(prev1, prev2 + x)  # skip x, or take it after i-2
    return prev1
C++
// Largest sum of elements with no two adjacent.
long long rob(const vector<int>& nums) {
    long long prev2 = 0, prev1 = 0;  // best totals up to i-2 and up to i-1
    for (int x : nums) {
        long long cur = max(prev1, prev2 + x);  // skip x, or take it after i-2
        prev2 = prev1;
        prev1 = cur;
    }
    return prev1;
}
Java
class Solution {
    // Largest sum of elements with no two adjacent.
    long rob(int[] nums) {
        long prev2 = 0, prev1 = 0; // best totals up to i-2 and up to i-1
        for (int x : nums) {
            long cur = Math.max(prev1, prev2 + x); // skip x, or take it after i-2
            prev2 = prev1;
            prev1 = cur;
        }
        return prev1;
    }
}
Go
// rob returns the largest sum of elements with no two adjacent.
func rob(nums []int) int {
	prev2, prev1 := 0, 0 // best totals up to i-2 and up to i-1
	for _, x := range nums {
		prev2, prev1 = prev1, max(prev1, prev2+x) // skip x, or take it after i-2
	}
	return prev1
}

Common variants

Problems at this stop also need the 2 shapes below. Open one to see when to switch to it; its code is tested in all four languages too.

Top-down recursion with a memoO(n) time · O(n) space (memo plus recursion stack)

Write the recursion for "how many ways, or how few, from position i on", then add a memo table, and you have the other way to write a DP. It is handier when the order of transitions is awkward or only some states are ever reached. LC 91 (Decode Ways), LC 70 (Climbing Stairs) and LC 343 (Integer Break) all work; in Python use functools.cache.

Python
from functools import cache


def num_decodings(s: str) -> int:
    """Ways to read a digit string as letters, 1 = A ... 26 = Z (LC 91)."""

    @cache
    def ways(i: int) -> int:  # ways to decode s[i:]
        if i == len(s):
            return 1
        if s[i] == "0":
            return 0  # no letter's code starts with 0
        total = ways(i + 1)  # read one digit
        if i + 1 < len(s) and int(s[i : i + 2]) <= 26:
            total += ways(i + 2)  # or two
        return total

    return ways(0)
C++
// Ways to read a digit string as letters, 1 = A ... 26 = Z (LC 91).
long long numDecodings(const string& s) {
    int n = s.size();
    vector<long long> memo(n + 1, -1);  // memo[i]: ways to decode s[i..], -1 = not computed yet
    function<long long(int)> ways = [&](int i) -> long long {
        if (i == n) return 1;
        if (memo[i] >= 0) return memo[i];
        if (s[i] == '0') return memo[i] = 0;  // no letter's code starts with 0
        long long total = ways(i + 1);  // read one digit
        if (i + 1 < n && stoi(s.substr(i, 2)) <= 26) total += ways(i + 2);  // or two
        return memo[i] = total;
    };
    return ways(0);
}
Java
class Solution {
    private Long[] memo; // memo[i]: ways to decode s[i..], null = not computed yet
    private String s;

    // Ways to read a digit string as letters, 1 = A ... 26 = Z (LC 91).
    long numDecodings(String s) {
        this.s = s;
        memo = new Long[s.length() + 1];
        return ways(0);
    }

    private long ways(int i) {
        if (i == s.length()) return 1;
        if (memo[i] != null) return memo[i];
        long total = 0;
        if (s.charAt(i) != '0') { // no letter's code starts with 0
            total = ways(i + 1); // read one digit
            if (i + 1 < s.length() && Integer.parseInt(s.substring(i, i + 2)) <= 26) total += ways(i + 2); // or two
        }
        return memo[i] = total;
    }
}
Go
// numDecodings returns the ways to read a digit string as letters, 1 = A ... 26 = Z (LC 91).
func numDecodings(s string) int {
	n := len(s)
	memo := make([]int, n+1) // memo[i]: ways to decode s[i:], -1 = not computed yet
	for i := range memo {
		memo[i] = -1
	}
	var ways func(i int) int
	ways = func(i int) int {
		if i == n {
			return 1
		}
		if memo[i] >= 0 {
			return memo[i]
		}
		total := 0
		if s[i] != '0' { // no letter's code starts with 0
			total = ways(i + 1) // read one digit
			if i+1 < n && (s[i]-'0')*10+(s[i+1]-'0') <= 26 {
				total += ways(i + 2) // or two
			}
		}
		memo[i] = total
		return total
	}
	return ways(0)
}
Split a circle into two linesO(n) time · O(1) space

When the array wraps around and the first and last cannot both be chosen (House Robber in a circle): split it into two plain lines, one without the last element and one without the first, run the linear DP on each and keep the better. LC 213 (House Robber II); the circular maximum subarray is handled differently, at the state-machine DP stop.

Python
def rob_circle(nums: list[int]) -> int:
    """House robber with the houses in a circle: the first and last are neighbours (LC 213)."""

    def rob_line(lo: int, hi: int) -> int:  # the plain robber on nums[lo:hi]
        prev2 = prev1 = 0
        for x in nums[lo:hi]:
            prev2, prev1 = prev1, max(prev1, prev2 + x)
        return prev1

    if len(nums) == 1:
        return nums[0]
    return max(rob_line(0, len(nums) - 1), rob_line(1, len(nums)))  # without the last, or without the first
C++
// House robber with the houses in a circle: the first and last are neighbours (LC 213).
int robCircle(const vector<int>& nums) {
    auto robLine = [&](int lo, int hi) {  // the plain robber on nums[lo, hi)
        int prev2 = 0, prev1 = 0;
        for (int i = lo; i < hi; i++) {
            int cur = max(prev1, prev2 + nums[i]);
            prev2 = prev1;
            prev1 = cur;
        }
        return prev1;
    };
    int n = nums.size();
    if (n == 1) return nums[0];
    return max(robLine(0, n - 1), robLine(1, n));  // without the last, or without the first
}
Java
class Solution {
    // House robber with the houses in a circle: the first and last are neighbours (LC 213).
    int robCircle(int[] nums) {
        int n = nums.length;
        if (n == 1) return nums[0];
        return Math.max(robLine(nums, 0, n - 1), robLine(nums, 1, n)); // without the last, or without the first
    }

    // The plain robber on nums[lo, hi).
    private int robLine(int[] nums, int lo, int hi) {
        int prev2 = 0, prev1 = 0;
        for (int i = lo; i < hi; i++) {
            int cur = Math.max(prev1, prev2 + nums[i]);
            prev2 = prev1;
            prev1 = cur;
        }
        return prev1;
    }
}
Go
// robCircle is the house robber with the houses in a circle: the first and last are neighbours (LC 213).
func robCircle(nums []int) int {
	robLine := func(line []int) int { // the plain robber on a line of houses
		prev2, prev1 := 0, 0
		for _, x := range line {
			prev2, prev1 = prev1, max(prev1, prev2+x)
		}
		return prev1
	}
	n := len(nums)
	if n == 1 {
		return nums[0]
	}
	return max(robLine(nums[:n-1]), robLine(nums[1:])) // without the last, or without the first
}

Why it works

  1. Optimal substructure: remove the last decision from the best answer for the first i elements, and what remains must be optimal for its subproblem; otherwise swapping in a better sub-answer would beat the best answer, a contradiction.
  2. Splitting by the last decision (rob house i or not, last step of 1 or 2) divides all plans into disjoint classes that cover everything, so taking a max or a sum neither misses nor double counts.
  3. Rolling variables work only when dp[i] depends on dp[i−1] and dp[i−2] alone, and the new value must be computed from the old ones before shifting them forward.

Say it in 30 seconds

When the interviewer asks you to talk it through: the approach, why it is correct, then the cost. One version in each language to read aloud a few times.

中文
动态规划我先用一句话定义状态,比如 dp[i] 表示用前 i 个元素能得到的最优值。然后按最后一个决策分类写转移:第 i 个选或不选,这几类互不重叠又覆盖所有方案,所以取最大值不会漏。正确性靠最优子结构:最优解去掉最后一步,剩下的也一定是子问题的最优解。如果只依赖前两项,就用两个变量滚动,空间降到 O(1)。
English
For DP I first define the state in one sentence, such as dp[i] being the best value using the first i elements. Then I write the transition by the last decision, take element i or not, and since those cases are disjoint and cover every plan, the max misses nothing. It is correct by optimal substructure: remove the last step from a best answer and what remains is a best answer to the smaller problem. When dp[i] needs only the previous two values, I roll two variables and use O(1) space.

Grade yourself

Grade your answer against the one above. Questions you have not mastered come back after 1, 3, 7 and 21 days, listed under My progress → Due for review. Kept on this device; sign in and it moves to your account.

Key points you covered (0 of 3)
How well did you know it?

Quick quiz

4 concept and complexity questions. Answered ones come back for spaced review along with the OA multiple-choice practice. Open the OA multiple-choice practice

4 questions
  1. Which two properties make a problem a good fit for dynamic programming?
  2. Which are true of top-down memoization and bottom-up tabulation? Select all that apply.
  3. What is the time complexity of this code?
    def fib(n):
        if n < 2:
            return n
        return fib(n - 1) + fib(n - 2)
  4. What is the time of the first call fib(n) (treating integer addition as O(1))?
    from functools import lru_cache
    
    @lru_cache(maxsize=None)
    def fib(n):
        if n < 2:
            return n
        return fib(n - 1) + fib(n - 2)

Your answers stay in this browser on this device; open OA multiple-choice practice signed in to keep them in your account.

Template drills

Drills cut from the templates above: put shuffled lines back in order, fill the blanked boundary conditions back in, or write a whole template from memory in an empty editor, run against this stop's tests and compared line by line. Another one gives a new drill.

These lines are shuffled. Tap a line to pick it, then tap another to swap them, until they read as the template does; the indentation is a hint.

Practice by stage

This stop's 10 Line 500 problems in three stages: Foundation, Core and Advanced. Each has a one-line approach; try it yourself before reading it.

Foundation 3

#ProblemApproachRating
509Fibonacci NumberCompare recursion, memoization, and rolling variables to understand repeated subproblems and explain time and space complexity.
70Climbing StairsDerive the counting recurrence from the final step and practice initialization for the empty prefix and smallest inputs.
746Min Cost Climbing StairsDistinguish states for reaching a position from states for paying a step's cost, accounting for two possible starting positions.Rating 1358

Core 5

#ProblemApproachRating
198House RobberModel adjacent exclusions through choosing or skipping and compress the full table to constant space.
213House Robber IIBreak circular dependence by fixing endpoint choices, checking single-element input and interval boundaries.
740Delete and EarnAggregate value frequencies and translate conflicts between neighboring values into the House Robber model.
91Decode WaysPartition decoding choices by the last one or two digits, handling zeros and invalid codes precisely.
2369Check if There is a Valid Partition For The ArrayTranslate fixed-size group rules into prefix reachability, distinguishing equal triples from consecutive increasing triples.Rating 1780

Advanced 2

#ProblemApproachRating
343Integer BreakDistinguish states requiring a split from states permitting further splits, and explain the connection between DP and the mathematical solution.
6502 Keys KeyboardDetermine the subproblem from the last copy operation and reduce the operation sequence to a factorization cost.