Skip to content
Tech Interview Prep
Technical interview guide

1-D Dynamic Programming

Breaking a problem into overlapping subproblems indexed by a single variable, solved once each and reused.

Minutes to read
3
Practice MCQs
25
Interview Q&A
25
Edition
v8
Editorial status
Reviewed

Scope: Language-neutral, with memoisation and recursion behaviour cited from CPython 3.14.

Overview

Curated: · Written: · Reviewed:

1-D Dynamic Programming

In one line

Dynamic programming answers an optimum or count by defining one state per index, writing a transition over the last decision, and computing each state once. Reach for it when subproblems overlap and their answers combine into the full answer.

Key definitions

  • State: the smallest set of parameters that determines the rest of the solution. Write it as an English sentence before any code.
  • Transition: the exhaustive, non-overlapping enumeration of the last decision.
  • Base case: the value of every state reachable without recursing. Impossible states get a sentinel such as negative infinity, not zero.
  • Optimal substructure: the optimum is built from subproblem optima.
  • Ending-here versus best-so-far: the value the recurrence extends versus the value the answer reports.
  • Pseudo-polynomial: running time polynomial in the numeric value of an input, such as O(nW) for knapsack.

Formulas and complexity

time=#states×cost per transition\mathrm{time} = \#\mathrm{states} \times \mathrm{cost\ per\ transition} 0/1 knapsack:O(nW) time,  O(W) space with one row\mathrm{0/1\ knapsack}: O(nW) \text{ time}, \; O(W) \text{ space with one row} LIS by tails:O(nlog⁡n) time,  O(n) space\mathrm{LIS\ by\ tails}: O(n \log n) \text{ time}, \; O(n) \text{ space}

How it works

Worked example: house robber, where no two adjacent houses can both be robbed. The state is dp[i], the best total over the first i houses. Skipping house i-1 inherits dp[i-1]. Robbing it adds a[i-1] to dp[i-2], because house i-2 is then forbidden. Base cases are dp[0] = 0 and dp[1] = a[0].

Trace on a = [2, 7, 9, 3, 1]:

  • dp[2] = max(2, 7) = 7
  • dp[3] = max(7, dp[1] + 9 = 11) = 11
  • dp[4] = max(11, dp[2] + 3 = 10) = 11
  • dp[5] = max(11, dp[3] + 1 = 12) = 12

The answer is 12, from robbing houses 0, 2 and 4.

Knapsack has a different take branch. Taking item i-1 adds its value to dp[i-1] at capacity W minus the item's weight, not to dp[i-2]. Do not reuse the house-robber shape for it.

Best for first i houses Skip house i-1: dp i-1 Rob house i-1: dp i-2 plus a i-1 Max of both Stored as dp i

Fill the table in dependency order. Recurrences that look backward fill upward; recurrences that look forward fill downward. Memoisation visits only reachable states but recurses to the depth of the dependency chain.

When to use and when not to

SituationChoiceReason
Overlapping subproblems and optimal substructureDynamic programmingCache hits and exact answers
A provable local rule (exchange argument)GreedyCheaper and correct for that problem only
Every configuration must be listedBacktrackingThe answer is the enumeration itself
Overlap exists but optimal substructure does notNeither as statedRecurrence is wrong, cache only hides it
Caller needs the chosen itemsKeep a decision per stateA rolled-up row cannot be walked back
State product too large for memoryRedesign the stateCompute the size before coding

Traps interviewers probe

  1. Zero as the base for an impossible state. Every amount looks reachable. Use a sentinel for unreachable states. For counting, the empty solution is 1, so dp[0] = 1.
  2. Kadane's initialised at zero. An all-negative array returns 0, but no empty subarray is allowed. Start from a[0] and test an all-negative input.
  3. Reporting the ending-here value. That is the best subarray ending at the last element. Track best separately and return it.
  4. Wrong loop nesting. Coins outermost counts combinations. Amounts outermost counts permutations. In 1-D knapsack, iterate capacity downward for 0/1 items and upward for unlimited copies.
  5. Collapsing the table, then reconstructing. A rolled-up row loses the choices. Keep a predecessor or decision per state. The LIS tails array gives the length only, not a valid subsequence.

Interview tips

Open by stating the state as one sentence, then the transition, then the base cases. Name the complexity as states times transition cost.

Expect these follow-ups: collapse the table to O(1) or O(W) space and say what is lost; reconstruct the chosen items; why greedy fails on coins [1, 3, 4] for 6 (greedy gives 4+1+1, the optimum is 3+3); why the knapsack bound is pseudo-polynomial; when the default recursion limit forces tabulation; and how a modulus must be applied at every step in counting problems.

30-second outline: "The state is the best total over the first i houses. Each house is either skipped, which inherits the previous state, or robbed, which adds to the state two back, because the neighbour is forbidden. Base cases are dp[0] = 0 and dp[1] = a[0]. I fill in increasing index order, so the time is O(n) states times O(1) transition, and the space drops to two variables if I do not need the choices. For 0/1 knapsack the take branch instead reads dp[i-1] at capacity W minus the item's weight."

Feedback on this overview

Log in free to save your progress and keep bookmarks and notes for a quick revision before your interview.