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.
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
// 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;
} def climb_stairs(n):
prev2, prev1 = 1, 1 # ways(0), ways(1)
for _ in range(2, n + 1):
prev2, prev1 = prev1, prev1 + prev2
return prev1
def minimize_cost(k, h):
n = len(h)
dp = [0] * n # dp[i] = cheapest way to reach stone i
for i in range(1, n):
dp[i] = min(dp[j] + abs(h[i] - h[j]) for j in range(max(0, i - k), i))
return dp[-1]
from bisect import bisect_left
def length_of_lis(nums):
tails = [] # tails[l] = smallest tail of an increasing run of length l + 1
for x in nums:
i = bisect_left(tails, x) # first tail >= x
if i == len(tails):
tails.append(x)
else:
tails[i] = x
return len(tails) // Climbing Stairs: ways(i) = ways(i - 1) + ways(i - 2)
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
int minimizeCost(int k, vector<int>& h) {
int n = h.size();
vector<int> dp(n, INT_MAX); // dp[i] = cheapest way to reach stone i
dp[0] = 0;
for (int i = 1; i < n; i++)
for (int j = max(0, i - k); j < i; j++)
dp[i] = min(dp[i], dp[j] + abs(h[i] - h[j]));
return dp[n - 1];
}
// LIS in O(n log n) with lower_bound on the tails
int lengthOfLIS(vector<int>& nums) {
vector<int> tails;
for (int x : nums) {
auto it = lower_bound(tails.begin(), tails.end(), x); // first tail >= x
if (it == tails.end()) tails.push_back(x);
else *it = x;
}
return tails.size();
} // Climbing Stairs: ways(i) = ways(i - 1) + ways(i - 2)
function climbStairs(n) {
let prev2 = 1, prev1 = 1; // ways(0), ways(1)
for (let i = 2; i <= n; i++) [prev2, prev1] = [prev1, prev1 + prev2];
return prev1;
}
// Minimal cost with jumps of up to k
function minimizeCost(k, h) {
const n = h.length, dp = new Array(n).fill(Infinity);
dp[0] = 0; // dp[i] = cheapest way to reach stone i
for (let i = 1; i < n; i++)
for (let 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
function lengthOfLIS(nums) {
const tails = [];
for (const x of nums) {
let lo = 0, hi = tails.length; // first tail >= x
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (tails[mid] < x) lo = mid + 1; else hi = mid;
}
tails[lo] = x; // extends when lo === tails.length
}
return tails.length;
} The variations
-
1Look back a fixed number of steps
The last move came from
i - 1,i - 2or up toi - 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.Now you solve -
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].Now you solve -
3Split the prefix into valid pieces
dp[i]= can (or in how many ways can) the firsticharacters be split. Try every last pieces[j..i): if it is valid anddp[j]holds, so doesdp[i]. Decode Ways only needs pieces of length 1 and 2.Now you solve- Word Break Medium Stuck? ▶ video
- Concatenated Words Hard Stuck? solution
-
4Longest increasing chain
dp[i]= the longest chain ending at itemi= 1 + the bestdp[j]over earlier items it can follow. That is O(n²). For plain numbers, thetailsarray with binary search gives O(n log n). Sort first when the order is yours to choose (envelopes, words by length).Now you solve -
5Jobs on a timeline: sort plus binary search
Sort jobs by end time.
dp[i]= best profit using the firstijobs = max(skip job i, its profit +dp[j]), wherejis the last job that ends before it starts, found by binary search.Now you solve -
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.
Now you solve- Frog Jump Hard Stuck? solution
- Race Car Hard Stuck? 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
0on its own is not a letter, and06is not a valid two-digit code. - Using the O(n log n) LIS
tailsarray as if it were the subsequence itself: only its length is meaningful.
Lesson done
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.