Linear recurrence relations, state machines, and optimal decision subproblems
561 problems·14 Easy·280 Medium·267 Hard
Pattern Study Guide & Cheat Sheet· O(n) [or O(n * amount)] · O(n) array, reducible to O(1) with rolling variables
▼
Break a sequential decision problem into overlapping subproblems governed by a recurrence relation dp[i] = f(dp[i-1], dp[i-2], ...), caching intermediate states to avoid exponential recomputation.
Core Invariant: State definition must capture all information needed for future transitions. E.g., `dp[i]` = best answer considering elements up to `i`. Once `dp[i]` is computed, prior steps never need re-evaluation.
Recognize it (Keywords & Signals)
Number of ways to reach step N / amount
Maximum profit without taking adjacent items (House Robber)
Minimum cost / coins to form total amount
Longest increasing subsequence
Word break / decode ways
When NOT to use
Decisions have circular dependencies or no optimal substructure (e.g. past decisions invalidate state without being captured in state index).
How to solve (Step-by-step)
1.Define state in plain words: what does `dp[i]` store?
2.Identify recurrence relation: how does `dp[i]` depend on `dp[i-1]`, `dp[i-2]`, etc.?
3.Identify base cases: `dp[0] = 0`, `dp[1] = ...`.
4.Determine computation order: iterate bottom-up from 1 to N.
5.Space optimization: if `dp[i]` only relies on the last K states, replace array with K variables for O(1) space.
Watch for (Interview Traps)
Array indexing off-by-one (e.g. allocating `dp` of size `n` instead of `n + 1` for 1-indexed amounts)
Initializing with 0 instead of `infinity` for minimization problems (e.g. Coin Change)
Premature space optimization before verifying the recurrence on edge cases
1D DP Tabulation & Space Optimization (House Robber)
def rob(nums: list[int]) -> int:
if not nums:
return 0
if len(nums) == 1:
return nums[0]
# State: dp[i] = max money robbing from house 0..i
# Transition: dp[i] = max(dp[i-1], dp[i-2] + nums[i])
# Space optimized: only need previous two values
prev2 = nums[0]
prev1 = max(nums[0], nums[1])
for i in range(2, len(nums)):
curr = max(prev1, prev2 + nums[i])
prev2 = prev1
prev1 = curr
return prev1
Cost
O(n) [or O(n * amount)] · O(n) array, reducible to O(1) with rolling variables (Reduces exponential 2^n recursion to linear O(n).)
What is the 1D Dynamic Programming pattern in coding interviews?
Linear recurrence relations, state machines, and optimal decision subproblems It is categorized under Advanced & DP and features 561 curated interview problems across Easy (14), Medium (280), and Hard (267) difficulties.
Which tech companies frequently test 1D Dynamic Programming?
How do I master the 1D Dynamic Programming pattern?
Start by studying the algorithmic strategy and template code, then practice Easy and Medium problems before attempting Hard problems under timed conditions.