1D (Linear) DP
State is a single index into a sequence; dp[i] is the best answer for the prefix (or suffix) ending at i.
You have not marked these as done yet. Read on anyway if they feel familiar; come back to them if something here does not land.
Overview
In 1D DP the state is one integer i, and dp[i] summarizes the best/count/feasibility for the first i elements (or for the prefix ending exactly at i, which is a subtly different and often more useful definition). Transitions look back a constant number of positions (dp[i-1], dp[i-2]) or all earlier positions (max over j < i), giving O(n) or O(n²) respectively.
This is the entry point to DP: Fibonacci Numbers, Climbing Stairs, House Robber, Kadane's Algorithm (max subarray), and Coin Change over the amount axis are all 1D. Longest Increasing Subsequence is 1D with an O(n) transition. Decode Ways, Jump Game, Word Break (index over the string) and "min cost climbing stairs" belong here too.
Typical constraints: n ≤ 10^5–10^6 for O(n) transitions, n ≤ 5000 for O(n²) "look at every earlier j" transitions.
Intuition
A mental model before the formal terms.
Walk along the array from left to right carrying a small backpack of facts about what you have already passed. For house robber the backpack holds two numbers: the best loot if you robbed the previous house, and the best if you did not. Each new house updates those two numbers; you never look further back.
The two flavours of dp[i] matter: "best over the whole prefix" is monotone and the answer is dp[n]; "best ending exactly at i" is not monotone and the answer is max over i — Kadane's Algorithm and Longest Increasing Subsequence use the latter because the "ending here" condition is what makes the transition local.
How it works
- State:
dp[i]= answer for elements0..i-1(prefix of lengthi), or for the segment ending at indexi. Say which one aloud; it fixes the base case and the final answer. - Transition: enumerate what happens to element
i: taken or skipped (dp[i] = max(dp[i-1], dp[i-2] + a[i])in house robber), extended or restarted (dp[i] = max(a[i], dp[i-1] + a[i])in Kadane), or which earlierjit attaches to (dp[i] = 1 + max dp[j] for j < i, a[j] < a[i]in LIS). - Base case:
dp[0]for the empty prefix (0,1way, ortrue), and sometimesdp[1]explicitly. - Order: increasing
i. Table: array ofn + 1. Optimization: if onlydp[i-1..i-k]is read, keepkvariables.
Why it works
Optimal substructure: the best solution for the prefix of length i either does not involve element i-1 (then it is the best for prefix i-1) or does, in which case removing that element leaves an optimal solution to a strictly shorter prefix. The transition enumerates these cases exhaustively.
Since i only decreases across a transition, evaluating in increasing i is a valid topological order.
Recognition
How to tell a problem wants this.
- A single array or string is processed left to right and each decision affects a bounded window of neighbours ("no two adjacent", "steps of 1 or 2", "decode 1 or 2 digits").
- Asks for the best contiguous or non-contiguous selection from a sequence, or the number of ways to segment/decode it.
- A greedy left-to-right pass is tempting but a counterexample exists (e.g.
[2, 7, 9, 3, 1]for house robber).
Interactive visualization
Play, step, change the input. ← → and space work too.
Showing the closely related House Robber visualization.
| 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|
| 2 | 7 | · | · | · | · | · |
1dp[0] = v[0]; dp[1] = max(v[0], v[1])2for i in 2 .. n-1:3 take = dp[i-2] + v[i]4 skip = dp[i-1]5 dp[i] = max(take, skip)6return dp[n-1]Pseudocode
1# house-robber: dp[i] = best loot from houses 0..i-12dp[0] = 0, dp[1] = a[0]3for i in 2..n:4 dp[i] = max(dp[i-1], dp[i-2] + a[i-1]) # skip house i-1, or rob it5return dp[n]Implementations
1# Representative problem: house robber (max sum of non-adjacent elements)2def rob(houses: list[int]) -> int:31 · Handle the empty case4 n = len(houses)5 if n == 0:6 return 072 · Table and base cases8 dp = [0] * (n + 1) # dp[i] = best loot from the first i houses9 dp[1] = houses[0]103 · Transition: skip house i-1, or rob it11 for i in range(2, n + 1):12 dp[i] = max(dp[i - 1], dp[i - 2] + houses[i - 1])134 · Read the answer14 return dp[n]15 16 175 · Space-optimized rolling variables18def rob_o1(houses: list[int]) -> int:19 prev2 = prev1 = 0 # dp[i-2], dp[i-1]20 for h in houses:21 prev2, prev1 = prev1, max(prev1, prev2 + h)22 return prev123 24 25if __name__ == "__main__":26 print(rob([2, 7, 9, 3, 1]), rob_o1([2, 7, 9, 3, 1])) # 12 12- Representative 1D DP:
dp[i]is the best loot from the firstihouses. [0] * (n + 1)builds the table with the basedp[0] = 0;dp[1] = houses[0].- The transition
max(dp[i-1], dp[i-2] + houses[i-1])is "skip" vs "rob" for housei-1. rob_o1uses tuple assignment to slide the two trackers forward in one statement.- Both print 12 for
[2, 7, 9, 3, 1].
prev2 = prev1 = 0chained assignment binds both names to the same immutable int — safe here, not safe with lists.- Built-in
maxon two ints is fine; for many candidates use a generator, not a temporary list. - Slices copy:
rob_o1(houses[1:])for House Robber II costs O(n) extra memory.
- Returning
dp[n - 1]instead ofdp[n]. - Using
houses[i]instead ofhouses[i - 1]with the prefix-length convention. - Writing the rolling update as two statements in the wrong order.
Complexity
LIS-style O(n²) transitions can sometimes be sped up with binary search or a segment tree.
Compare growth rates in the Complexity Explorer →When to use — and when not to
- One sequence, decisions depend on a bounded window of previous positions.
- Answer for a prefix is a function of answers for shorter prefixes.
- The problem is a chain of "take / skip" or "extend / restart" choices.
- Two sequences interact (alignment, common subsequence) — that needs 2D (Two-Sequence) DP.
- The decision at
idepends on an unbounded summary of the past that a single index cannot capture (e.g. which items were taken) — add a dimension or use Bitmask DP. - Contiguous max sum with all-positive numbers or a simple greedy suffices — no DP needed.
Alternatives
Common mistakes
- Confusing "best for prefix of length
i" with "best ending ati" — the base cases and final answer differ. - Returning
dp[n-1]when the table is sizedn + 1with a zero base, or vice versa. - Forgetting that "ending here" DPs need
max over all i, notdp[n-1]. - Initializing
dp[0]to0in counting problems where the empty prefix has exactly one way.
Interview patterns
- House Robber I/II (circular: run twice, excluding first or last).
- Decode Ways, Climbing Stairs with variable steps, Min Cost Climbing Stairs.
- Word Break with
dp[i]= "prefix of lengthiis segmentable". - Jump Game (feasibility) and Jump Game II (min jumps, which is also solvable greedily).
- Coin ChangeIntermediate
Example problems
Check yourself
Answer out loud or on paper first, then compare. These come from the interview questions linked to this lesson.
How do you decide between BFS, DFS, Dijkstra, and Dynamic Programming?
Show a strong answerHide the answer
A strong candidate reframes the question: each of these answers a specific question about a specific kind of graph. What am I being asked — reachability, a shortest path, an ordering, an optimal value — and what does the graph look like — weighted or not, cyclic or not, explicit or implicit (states in a puzzle are a graph too).
Breadth-First Search (BFS) answers "fewest edges" and explores by distance layers; it is optimal only when every edge costs the same. Depth-First Search (DFS) answers structural questions — does a path exist, are there cycles, what is a topological order, which components exist — and is the natural backbone of backtracking. Dijkstra's Algorithm is BFS generalized to non-negative weights: replace the queue with a Priority Queue and you are done; its correctness argument breaks the moment a negative edge appears. Dynamic Programming is shortest (or best) path on a DAG: the subproblem dependency graph must be acyclic so subproblems can be solved in one topological pass.
The unifying view: all four are "process states in a valid order and relax transitions". BFS orders by hop count, Dijkstra by tentative distance, DP by topological order of subproblems, DFS by discovery. If the state graph has cycles and weights, you cannot use DP and need Dijkstra; if it is acyclic, DP is simpler and linear; if weights are uniform, BFS is both simpler and faster than Dijkstra.
Full interview question, with follow-ups and red flags →Interviewers ask about space complexity. When does it actually matter, and how do you reason about it?
Show a strong answerHide the answer
Space complexity counts auxiliary memory beyond the input: explicit structures (hash maps, DP tables), the recursion stack, and sometimes the output itself if it is large. A strong candidate lists all three; the recursion stack is the one people forget — recursive DFS on a tree is
O(h), and on a degenerate treeh = n.It matters in three situations. Memory limits: a
10^5 × 10^5DP table is10^{10}cells — impossible — so you need a 1D rolling array or a different state. Streams: if data is unbounded you must keepO(k)orO(1)state (top-kwith a heap, reservoir sampling). Explicit requirements: "in place" or "O(1)extra space" forces two pointers, index marking, or bit tricks instead of a hash set.The standard reductions: a 2D DP that only reads the previous row becomes two rows (Grid DP, Longest Common Subsequence); a hash set used for "seen" can become a sort plus adjacent comparison when reordering is allowed; recursion becomes an explicit loop; and a full array of prefix sums becomes a running sum when only the current prefix is needed. They also weigh the tradeoff honestly: an
Full interview question, with follow-ups and red flags →O(n)hash map that turnsO(n^2)intoO(n)is almost always worth it.Edge weights are only 0 and 1. What changes?
Show a strong answerHide the answer
0-1 BFS with a deque: push 0-cost neighbours to the front, 1-cost to the back.
Full interview question, with follow-ups and red flags →O(V + E)instead of Dijkstra's log factor.