DP on Sequences
Linear DP (house robber, decode ways), longest increasing subsequence, two-sequence DP (LCS, edit distance) and state machines (stock problems).
Most interview DP happens on sequences: arrays and strings. Four shapes cover nearly all of them. Identify which one you're in and the state definition follows.
| Shape | State | Examples |
|---|---|---|
| Linear | dp[i] = answer for the prefix ending at / up to i | Climbing stairs, house robber, decode ways, max subarray |
| LIS-style | dp[i] = best subsequence ending at i, looking back at all j less than i | LIS, Russian dolls, largest divisible subset |
| Two sequences | dp[i][j] = answer for prefixes a[0..i) and b[0..j) | LCS, edit distance, distinct subsequences, regex matching |
| State machine | dp[i][state] = best at i while in a given state | Stock buy/sell with cooldown, fees, k transactions |
1. Linear DP: house robber
You can't rob two adjacent houses. Either skip house i (dp[i−1]) or rob it (dp[i−2] + a[i]). Only the last two values are ever needed.
int rob(int[] a) {
int prev2 = 0, prev1 = 0; // dp[i-2], dp[i-1]
for (int x : a) {
int cur = Math.max(prev1, prev2 + x);
prev2 = prev1;
prev1 = cur;
}
return prev1;
}def rob(a):
prev2 = prev1 = 0
for x in a:
prev2, prev1 = prev1, max(prev1, prev2 + x)
return prev1function rob(a: number[]): number {
let prev2 = 0, prev1 = 0;
for (const x of a) [prev2, prev1] = [prev1, Math.max(prev1, prev2 + x)];
return prev1;
}Decode ways has the same skeleton: dp[i] = (one-digit valid ? dp[i−1] : 0) + (two-digit valid ? dp[i−2] : 0).
2. Longest increasing subsequence
O(n²) DP: dp[i] = 1 + max(dp[j]) over j less than i with a[j] < a[i]. The O(n log n) version keeps tails[k] = the smallest possible tail of an increasing subsequence of length k + 1, and binary searches where each element fits.
int lengthOfLIS(int[] a) {
int[] tails = new int[a.length];
int len = 0;
for (int x : a) {
int lo = 0, hi = len;
while (lo < hi) { // first tail >= x
int mid = (lo + hi) >>> 1;
if (tails[mid] < x) lo = mid + 1; else hi = mid;
}
tails[lo] = x;
if (lo == len) len++;
}
return len;
}from bisect import bisect_left
def length_of_lis(a):
tails = []
for x in a:
i = bisect_left(tails, x)
if i == len(tails):
tails.append(x)
else:
tails[i] = x
return len(tails)function lengthOfLIS(a: number[]): number {
const tails: number[] = [];
for (const x of a) {
let lo = 0, hi = tails.length;
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (tails[mid] < x) lo = mid + 1; else hi = mid;
}
tails[lo] = x;
}
return tails.length;
}3. Two sequences: LCS and edit distance
Compare the last characters of both prefixes. If they match, extend the diagonal; otherwise take the best of dropping a character from one side.
int minDistance(String a, String b) {
int m = a.length(), n = b.length();
int[][] dp = new int[m + 1][n + 1];
for (int i = 0; i <= m; i++) dp[i][0] = i; // delete everything
for (int j = 0; j <= n; j++) dp[0][j] = j; // insert everything
for (int i = 1; i <= m; i++)
for (int j = 1; j <= n; j++)
dp[i][j] = a.charAt(i - 1) == b.charAt(j - 1)
? dp[i - 1][j - 1]
: 1 + Math.min(dp[i - 1][j - 1], // replace
Math.min(dp[i - 1][j], // delete
dp[i][j - 1])); // insert
return dp[m][n];
}def min_distance(a, b):
m, n = len(a), len(b)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m + 1):
dp[i][0] = i
for j in range(n + 1):
dp[0][j] = j
for i in range(1, m + 1):
for j in range(1, n + 1):
if a[i - 1] == b[j - 1]:
dp[i][j] = dp[i - 1][j - 1]
else:
dp[i][j] = 1 + min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1])
return dp[m][n]function minDistance(a: string, b: string): number {
const m = a.length, n = b.length;
const dp = Array.from({ length: m + 1 }, (_, i) =>
Array.from({ length: n + 1 }, (_, j) => (i === 0 ? j : j === 0 ? i : 0)));
for (let i = 1; i <= m; i++)
for (let j = 1; j <= n; j++)
dp[i][j] = a[i - 1] === b[j - 1]
? dp[i - 1][j - 1]
: 1 + Math.min(dp[i - 1][j - 1], dp[i - 1][j], dp[i][j - 1]);
return dp[m][n];
}4. State machine: stock problems
Define states for what you hold and update all of them each day. With cooldown: hold, sold (just sold, must rest), rest.
int maxProfit(int[] prices) { // with cooldown
int hold = Integer.MIN_VALUE / 2, sold = 0, rest = 0;
for (int p : prices) {
int prevSold = sold;
sold = hold + p;
hold = Math.max(hold, rest - p);
rest = Math.max(rest, prevSold);
}
return Math.max(sold, rest);
}def max_profit(prices):
hold, sold, rest = float("-inf"), 0, 0
for p in prices:
hold, sold, rest = max(hold, rest - p), hold + p, max(rest, sold)
return max(sold, rest)function maxProfit(prices: number[]): number {
let hold = -Infinity, sold = 0, rest = 0;
for (const p of prices) [hold, sold, rest] = [Math.max(hold, rest - p), hold + p, Math.max(rest, sold)];
return Math.max(sold, rest);
}The same machine with a fee subtracted on sell, or with a transaction counter k as an extra dimension, solves the whole stock family.
- Climbing Stairseasy
- House Robbermedium
- House Robber IIrun twice: skip first / skip lastmedium
- Decode Waysmedium
- Maximum Product Subarraytrack min and maxmedium
- Longest Increasing Subsequencemedium
- Longest Common Subsequencemedium
- Edit Distancemedium
- Best Time to Buy and Sell Stock with Cooldownmedium
- Longest Palindromic SubsequenceLCS with the reversemedium
- Russian Doll Envelopessort, then LIShard
- Distinct Subsequenceshard
- Regular Expression Matchinghard
- Best Time to Buy and Sell Stock IVk transactionshard
- Four shapes: linear, LIS-style, two-sequence, state machine.
- Linear DP usually needs only the last one or two values.
- LIS in O(n log n) with
tailsand binary search. - Two-sequence DP: a padded (m+1) × (n+1) table, compare the last characters.
- State machines: one variable per state, all updated each step.