Dynamic Programming · Pattern 1 of 12

1D DP: the answer at i from earlier answers

The state is one index: dp[i] is the answer for the first i items (or for ending at item i). Each state looks back at a few earlier states, or at all of them, and combines them.

6 variations · 21 problems · 7 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Count the ways to reach the end of a line of steps or characters
  • Min cost to reach position i, moving forward by allowed jumps
  • Split a string or array into valid pieces
  • Longest chain where each item must beat the one before it

The template

1D DP
// Climbing Stairs: ways(i) = ways(i - 1) + ways(i - 2). Only the last two values are needed.
int climbStairs(int n) {
    int prev2 = 1, prev1 = 1;              // ways(0), ways(1)
    for (int i = 2; i <= n; i++) {
        int cur = prev1 + prev2;
        prev2 = prev1;
        prev1 = cur;
    }
    return prev1;
}

// Minimal cost with jumps of up to k: dp[i] = min over j in [i - k, i - 1] of dp[j] + |h[i] - h[j]|
int minimizeCost(int k, int[] h) {
    int n = h.length;
    int[] dp = new int[n];                 // dp[i] = cheapest way to reach stone i; dp[0] = 0
    for (int i = 1; i < n; i++) {
        dp[i] = Integer.MAX_VALUE;
        for (int j = Math.max(0, i - k); j < i; j++)
            dp[i] = Math.min(dp[i], dp[j] + Math.abs(h[i] - h[j]));
    }
    return dp[n - 1];
}

// LIS in O(n log n): tails[len] = smallest tail of an increasing subsequence of length len + 1
int lengthOfLIS(int[] nums) {
    int[] tails = new int[nums.length];
    int len = 0;
    for (int x : nums) {
        int lo = 0, hi = len;              // first tail >= x
        while (lo < hi) {
            int mid = (lo + hi) / 2;
            if (tails[mid] < x) lo = mid + 1; else hi = mid;
        }
        tails[lo] = x;                     // x extends a chain or makes a tail smaller
        if (lo == len) len++;
    }
    return len;
}

The variations

  1. 1Look back a fixed number of steps

    The last move came from i - 1, i - 2 or up to i - k. Add the ways (counting) or take the cheapest (cost). When only the last two values are used, keep two variables instead of an array. Delete and Earn turns into this once you bucket points by value.

  2. 2Build from the previous row or smaller sizes

    Each row of Pascal's triangle comes from the row above: row[j] = prev[j - 1] + prev[j]. Unique BSTs pick each value as the root and multiply the counts of the left and right sizes: dp[n] = sum dp[i - 1] * dp[n - i].

  3. 3Split the prefix into valid pieces

    dp[i] = can (or in how many ways can) the first i characters be split. Try every last piece s[j..i): if it is valid and dp[j] holds, so does dp[i]. Decode Ways only needs pieces of length 1 and 2.

  4. 4Longest increasing chain

    dp[i] = the longest chain ending at item i = 1 + the best dp[j] over earlier items it can follow. That is O(n²). For plain numbers, the tails array with binary search gives O(n log n). Sort first when the order is yours to choose (envelopes, words by length).

  5. 5Jobs on a timeline: sort plus binary search

    Sort jobs by end time. dp[i] = best profit using the first i jobs = max(skip job i, its profit + dp[j]), where j is the last job that ends before it starts, found by binary search.

  6. 6A state with more than an index

    Sometimes position alone is not enough. Paint House needs the colour of the last house, Frog Jump needs the size of the last jump, Race Car works on the distance still to cover. Add what the next move depends on to the state.

    Worked example Paint House Medium Read the solution

Mistakes to avoid

  • Off-by-one in the meaning of dp[i]: "the first i characters" and "ending at index i" give different base cases. Pick one and say it out loud.
  • Decode Ways: a 0 on its own is not a letter, and 06 is not a valid two-digit code.
  • Using the O(n log n) LIS tails array as if it were the subsequence itself: only its length is meaningful.
Next: Pick or not pick: House Robber →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.