Notes
All notes

Dynamic Programming (DSA Core #7)

Dynamic programming is recursion with memory. You write the brute-force recurrence, notice that it recomputes the same states, and store the answers. The hard part is not the code — it is naming the state and proving that the transition covers every case.

Every DP answer in an interview has four parts: the state, the transition, the base case, and the evaluation order. If you can say those four sentences, the code writes itself. If you cannot, no amount of trying will make it correct.

Overlapping subproblems and optimal substructure

Fibonacci is the smallest example with overlap:

long long fib(int n) {                  // exponential: ~1.6^n calls
    if (n <= 1) return n;
    return fib(n - 1) + fib(n - 2);
}

fib(n-2) is computed inside both branches, and those duplicates multiply. The call tree has about \(\phi^n\) nodes, \(\phi \approx 1.618\), so fib(50) is 20 billion calls for a 50-step recurrence.

Two properties make DP applicable:

If subproblems do not overlap, memoization does nothing (divide and conquer). If optimal substructure fails, a locally optimal choice does not lead to a globally optimal answer, and you need a different state or a different technique.

The number of distinct states is the real measure of cost. Memoization turns \(\phi^n\) into \(n\) states, one computation each.

QQuestionWhy doesn’t merge sort benefit from memoization?
ASolution

Its subproblems are disjoint: each array segment is sorted once, so there are no repeated states to cache. DP needs overlap.

The four questions

Take “minimum coins to make amount”. Answer in order:

  1. State: dp[x] = fewest coins summing to exactly x.
  2. Transition: dp[x] = 1 + min(dp[x - c]) over all coins c <= x.
  3. Base case: dp[0] = 0; unreachable amounts are INF.
  4. Order: increasing x, because dp[x] depends on smaller amounts.

Notice that the order follows from the transition: dependencies point to smaller indices, so a single left-to-right loop works. That is the general rule — draw the dependency edge for every term in the transition, and the loop order is any topological order of that graph.

QQuestionWhat goes wrong if the base case is dp[0] = 1 for minimum coins?
ASolution

Every answer becomes one less than the truth, because “1 coin” is credited to the empty sum. dp[0] = 0 for “minimum cost”, dp[0] = 1 only for “count of ways”.

Memoization versus tabulation

Memoization keeps the recursive shape and caches results. Tabulation fills a table iteratively.

// memoization: top-down
unordered_map<int,long long> memo;
long long fibMemo(int n) {
    if (n <= 1) return n;
    auto it = memo.find(n);
    if (it != memo.end()) return it->second;
    return memo[n] = fibMemo(n - 1) + fibMemo(n - 2);
}

// tabulation: bottom-up
long long fibTable(int n) {
    vector<long long> dp(n + 1, 0);
    dp[0] = 0; if (n >= 1) dp[1] = 1;
    for (int i = 2; i <= n; ++i) dp[i] = dp[i - 1] + dp[i - 2];
    return dp[n];
}
Memoization Tabulation
Direction top-down bottom-up
Computes only reachable states every state in the table
Recursion yes, stack depth risk no
Base cases handled naturally must be set explicitly
Space cache + call stack table, often reducible
Order implicit you choose it

Top-down is easier to derive from the brute force. Bottom-up is easier to optimize and cannot stack-overflow. In an OA, write the recurrence first, then decide.

Converting recursion to iteration is mechanical: identify the parameters, allocate an array with those dimensions, set the base cases, and loop in the opposite order of the recursion’s return path. For dp(i, j) depending on (i-1, j) and (i, j-1), iterate i ascending and j ascending.

QQuestionWhen can memoization compute fewer states than tabulation?
ASolution

When the reachable state space is a small part of the table — for example a DP over (index, remaining) where remaining can only take a few values. Tabulation loops over every cell.

Evaluation order and space optimization

The dependency graph decides the order, and it also decides what you can throw away. If dp[i][*] depends only on dp[i-1][*], two rows are enough.

// 2D
vector<vector<int>> dp(n, vector<int>(m));
// rolling 1D: dp[j] is the previous row before the update, the current row after
for (int i = 0; i < n; ++i)
    for (int j = 0; j < m; ++j)
        dp[j] = ...;      // uses dp[j] (above) and dp[j-1] (left, already updated)

Two rules:

Getting that direction backwards is the single most common 1D-DP bug.

QQuestionWhy does 0/1 knapsack iterate capacity downward?
ASolution

Descending means dp[c - w] still holds the previous item’s value, so each item is used at most once. Ascending lets the same item be reused (unbounded knapsack).

One-dimensional DP

Climbing stairs. One or two steps at a time; count the ways.

\[ dp[i] = dp[i-1] + dp[i-2], \qquad dp[0] = 1,\ dp[1] = 1 \]

int climbStairs(int n) {
    int a = 1, b = 1;                  // dp[0], dp[1]
    for (int i = 2; i <= n; ++i) {
        int c = a + b;
        a = b; b = c;
    }
    return b;
}

House robber. Take non-adjacent values to maximize the sum.

\[ dp[i] = \max(dp[i-1],\ dp[i-2] + a[i]) \]

Either skip house i (keep dp[i-1]) or take it (dp[i-2] + a[i]). Two variables suffice. The circular variant (first and last are adjacent) is two linear passes: one excluding the first house, one excluding the last.

The pattern in both: a single sequence, a decision per element, and a constant window of history. If a 1D DP needs more than a few previous values, name them explicitly rather than indexing a big array.

QQuestionHouse robber with values [2, 7, 9, 3, 1] — what is the answer and

the state after each step?

ASolution

12, from houses 1 and 3 (7 + 9 is invalid; 2 + 9 + 1 = 12). dp = 2, 7, 11, 11, 12.

Two-dimensional and grid DP

Unique paths in an m × n grid moving right or down:

\[ dp[i][j] = dp[i-1][j] + dp[i][j-1], \qquad dp[0][j] = dp[i][0] = 1 \]

The last move argument: you arrive from above or from the left, those sets are disjoint, and every path is in one of them. That is a correctness proof, not a hand wave — the two cases cover all paths exactly once.

int uniquePaths(int m, int n) {
    vector<int> dp(n, 1);                 // first row is all 1
    for (int i = 1; i < m; ++i)
        for (int j = 1; j < n; ++j)
            dp[j] += dp[j - 1];           // above + left, in place
    return dp[n - 1];
}

dp[j] before the update is the cell above, and dp[j-1] is the cell to the left, already updated this row. That in-place semantics is worth saying out loud if asked.

Minimum path sum is the same shape with min instead of +, and grid DP with obstacles sets blocked cells to 0 (paths) or infinity (cost). The first row and column need separate handling in the min version, because there is only one way to reach them.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  c/.style={draw, thick, minimum size=0.72cm, font=\small\bfseries}]
  \node[c, fill=blue!8] at (0,0) {1};
  \node[c, fill=blue!8] at (0.78,0) {1};
  \node[c, fill=blue!8] at (1.56,0) {1};
  \node[c, fill=blue!8] at (2.34,0) {1};
  \node[c, fill=blue!8] at (0,-0.78) {1};
  \node[c, fill=blue!8] at (0,-1.56) {1};
  \node[c, fill=orange!18] at (0.78,-0.78) {2};
  \node[c] at (1.56,-0.78) {3};
  \node[c] at (2.34,-0.78) {4};
  \node[c] at (0.78,-1.56) {3};
  \node[c] at (1.56,-1.56) {6};
  \node[c] at (2.34,-1.56) {10};
  \draw[->, thick, orange] (1.0,-0.4) -- (1.0,-0.55);
  \draw[->, thick, green!45!black] (0.45,-0.78) -- (0.62,-0.78);
  \node[font=\scriptsize, anchor=north] at (1.17,-2.1) {row 0 and column 0 are given: one way};
  \node[font=\scriptsize, text=orange!80!black, anchor=west] at (1.3,-0.5) {above};
  \node[font=\scriptsize, text=green!45!black, anchor=south] at (0.55,-0.95) {left};
\end{tikzpicture}
QQuestionWhy is the space-optimized unique-paths loop dp[j] += dp[j-1] and

not dp[j] += dp[j-1] + dp[j]?

ASolution

dp[j] already holds the value from above before the assignment. Adding it again double-counts that path.

Knapsack

0/1 knapsack. Items with weight and value, capacity W, each item at most once.

\[ dp[c] = \max(dp[c],\ dp[c - w_i] + v_i), \qquad c \text{ descending} \]

int knapsack(const vector<int>& w, const vector<int>& v, int W) {
    vector<int> dp(W + 1, 0);
    for (int i = 0; i < (int)w.size(); ++i)
        for (int c = W; c >= w[i]; --c)
            dp[c] = max(dp[c], dp[c - w[i]] + v[i]);
    return dp[W];
}

Unbounded knapsack. Same recurrence with c ascending, so an item can be taken again. This is the difference between “each item once” and “any number of each”.

Subset sum and partition. Values are booleans instead of maxima. “Can a subset sum to S” is 0/1 knapsack with value equal to weight. “Partition into two equal halves” is subset sum with S = total/2; odd totals are immediately impossible.

bool canPartition(const vector<int>& a) {
    int total = accumulate(a.begin(), a.end(), 0);
    if (total % 2) return false;
    int target = total / 2;
    vector<char> dp(target + 1, false);
    dp[0] = true;
    for (int x : a)
        for (int s = target; s >= x; --s)
            dp[s] = dp[s] || dp[s - x];
    return dp[target];
}
\begin{tikzpicture}[font=\rmfamily, >=stealth,
  c/.style={draw, thick, minimum width=0.62cm, minimum height=0.52cm, font=\scriptsize}]
  \foreach \i in {0,...,6} {
    \node[c, fill=gray!6] at (\i*0.65,0) {\i};
  }
  \node[font=\scriptsize, anchor=east] at (-0.4,0) {capacity};
  \foreach \i/\val in {0/1,1/1,2/1,3/1,4/1,5/1,6/1} {
    \node[c] at (\i*0.65,-0.72) {\val};
  }
  \node[font=\scriptsize, anchor=east] at (-0.4,-0.72) {dp};
  \draw[->, very thick, orange] (3.25,-0.35) -- (3.25,-0.62);
  \node[font=\scriptsize, text=orange!80!black, anchor=south] at (3.25,-0.32) {ascending = reuse};
  \draw[->, very thick, blue!60] (1.95,-1.05) -- (1.95,-0.4);
  \node[font=\scriptsize, text=blue!60!black, anchor=north] at (1.95,-1.1) {descending = once};
\end{tikzpicture}
QQuestionWhy does subset sum need the capacity loop descending?
ASolution

Descending keeps dp[s - x] from the previous item’s row, so each element is used at most once. Ascending would allow the same element twice.

Coin change

Two different problems share the name:

int minCoins(const vector<int>& coins, int amount) {
    const int INF = 1e9;
    vector<int> dp(amount + 1, INF);
    dp[0] = 0;
    for (int x = 1; x <= amount; ++x)
        for (int c : coins)
            if (c <= x && dp[x - c] + 1 < dp[x]) dp[x] = dp[x - c] + 1;
    return dp[amount] == INF ? -1 : dp[amount];
}

int countWays(const vector<int>& coins, int amount) {
    vector<long long> dp(amount + 1, 0);
    dp[0] = 1;
    for (int c : coins)                 // coins outer: combinations
        for (int x = c; x <= amount; ++x)
            dp[x] += dp[x - c];
    return (int)dp[amount];
}

Coins outer counts combinations (1+2 and 2+1 are the same). Amount outer counts permutations (they are different sequences). Both are “unbounded knapsack”; only the loop nesting changes.

The counterexample that kills greedy is coins = {1, 3, 4}, amount = 6: greedy takes 4 + 1 + 1 = 3 coins, optimal is 3 + 3 = 2. Canonical coin systems (like US denominations) happen to make greedy work, but a problem cannot assume that unless it says so.

QQuestioncoins = {2}, amount = 3. What do min-coins and count-ways

return?

ASolution

Min coins: -1 (unreachable, dp[3] stays at infinity). Ways: 0, because no combination sums to 3.

Longest common subsequence

Subsequence means not necessarily contiguous. The state is a pair of prefixes.

\[ dp[i][j] = \begin{cases} dp[i-1][j-1] + 1 & a[i-1] = b[j-1] \\ \max(dp[i-1][j],\ dp[i][j-1]) & \text{otherwise} \end{cases} \]

int lcs(const string& a, const string& b) {
    int n = a.size(), m = b.size();
    vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0));
    for (int i = 1; i <= n; ++i)
        for (int j = 1; j <= m; ++j) {
            if (a[i-1] == b[j-1]) dp[i][j] = dp[i-1][j-1] + 1;
            else dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
        }
    return dp[n][m];
}

Base case dp[0][*] = dp[*][0] = 0 (an empty string has no common subsequence). Order: both indices ascending, since the cell reads up, left, and up-left.

If the characters match, using them in the LCS is optimal. If they do not, at least one of them is unused, so the answer is the better of dropping either.

The rolling version keeps one row, but then reconstructing the actual subsequence is no longer possible without the full table. Reconstruct by walking back from dp[n][m], moving diagonally on a match and toward the larger neighbour otherwise.

QQuestionWhy is LCS not the same as longest common substring?
ASolution

A substring must be contiguous, so a mismatch resets the run: dp[i][j] = dp[i-1][j-1] + 1 on match and 0 otherwise. LCS keeps the best prefix answer across mismatches.

Edit distance

Three operations: insert, delete, replace. State is the same pair of prefixes.

\[ dp[i][j] = \begin{cases} dp[i-1][j-1] & a[i-1] = b[j-1] \\ 1 + \min\big(dp[i-1][j],\ dp[i][j-1],\ dp[i-1][j-1]\big) & \text{otherwise} \end{cases} \]

int editDistance(const string& a, const string& b) {
    int n = a.size(), m = b.size();
    vector<vector<int>> dp(n + 1, vector<int>(m + 1));
    for (int i = 0; i <= n; ++i) dp[i][0] = i;   // delete all
    for (int j = 0; j <= m; ++j) dp[0][j] = j;   // insert all
    for (int i = 1; i <= n; ++i)
        for (int j = 1; j <= m; ++j) {
            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],      // delete from a
                                     dp[i][j-1],      // insert into a
                                     dp[i-1][j-1]});  // replace
        }
    return dp[n][m];
}

What each term means is the part worth memorizing: dp[i-1][j] means a[i-1] was deleted, dp[i][j-1] means b[j-1] was inserted, dp[i-1][j-1] means a replacement. The base cases are “turn a prefix into the empty string”, which costs one operation per character.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  c/.style={draw, thick, minimum size=0.6cm, font=\scriptsize}]
  \node[font=\scriptsize\bfseries] at (0,0.62) {};
  \foreach \ch [count=\j from 1] in {c,a,t} \node[font=\scriptsize\bfseries] at (\j*0.65,0.62) {\ch};
  \foreach \ch [count=\i from 1] in {c,u,t} \node[font=\scriptsize\bfseries, anchor=east] at (-0.18,-\i*0.65) {\ch};
  \foreach \i/\row in {0/{0,1,2,3},1/{0,1,1,2},2/{2,1,1,2},3/{3,2,2,1}} {
    \foreach \val [count=\j from 0] in \row {
      \node[c, fill=blue!7] at (\j*0.65,-\i*0.65) {\val};
    }
  }
  \node[font=\scriptsize, anchor=north] at (0.98,-2.75) {"cut" vs "cat": one replace};
\end{tikzpicture}

Edit distance is the base of a family: “one edit away” (check length difference and count mismatches), delete-only distance (longest common subsequence), and weighted edits.

QQuestionWhy does a match not cost min(...) or anything else?
ASolution

Matching characters need no operation, and using them cannot hurt: skipping a matched pair gives a solution to a subproblem that is no better, by an exchange argument.

Longest increasing subsequence

\(O(n^2)\) is the direct DP. \(O(n \log n)\) uses patience sorting.

int lisSlow(const vector<int>& a) {            // O(n^2)
    vector<int> dp(a.size(), 1);
    int best = 0;
    for (int i = 0; i < (int)a.size(); ++i) {
        for (int j = 0; j < i; ++j)
            if (a[j] < a[i]) dp[i] = max(dp[i], dp[j] + 1);
        best = max(best, dp[i]);
    }
    return best;
}

int lisFast(const vector<int>& a) {            // O(n log n)
    vector<int> tails;                         // tails[k] = smallest tail of a length k+1 run
    for (int x : a) {
        auto it = lower_bound(tails.begin(), tails.end(), x);
        if (it == tails.end()) tails.push_back(x);
        else *it = x;
    }
    return (int)tails.size();
}

tails is not a subsequence; it is the best ending value for each length. The greedy replacement “smaller tail is always at least as good” is what makes it correct, and it is an exchange argument: any future element that extends a larger tail also extends the smaller one.

Use upper_bound instead of lower_bound for non-decreasing subsequences. That single difference is a common hidden test case.

QQuestionWhy does tails stay sorted?
ASolution

Each new value replaces the first tail that is at least as large, which preserves non-decreasing order. Appending happens only when the value is larger than all tails.

String DP

Most string DP is prefix-pair DP (LCS, edit distance) or interval DP (palindromes). Two more shapes are worth having:

Word break. dp[i] = prefix of length i can be segmented.

bool wordBreak(const string& s, const unordered_set<string>& dict) {
    int n = s.size();
    vector<char> dp(n + 1, false);
    dp[0] = true;
    for (int i = 1; i <= n; ++i)
        for (int j = 0; j < i; ++j)
            if (dp[j] && dict.count(s.substr(j, i - j))) { dp[i] = true; break; }
    return dp[n];
}

Complexity is \(O(n^2 \cdot L)\) with substr copies; a trie brings it to \(O(n^2)\).

Palindromic substrings / partitions. isPal[l][r] is an interval DP: isPal[l][r] = s[l] == s[r] && (r - l < 2 || isPal[l+1][r-1]). Then dp[i] = minimum cuts for the prefix, trying every palindrome ending at i.

QQuestionWhy is wordBreak’s inner loop over j and not over dictionary

words?

ASolution

Iterating split points is \(O(n^2)\) regardless of dictionary size. Iterating words costs \(O(n \cdot |dict| \cdot L)\) and is worse when the dictionary is large.

Interval DP

State is a range [l, r], transition picks a split or a last operation inside it, and the order is by increasing length because [l, r] depends on shorter ranges.

Burst balloons (with virtual 1s at both ends):

\[ dp[l][r] = \max_{l < k < r}\big(dp[l][k] + dp[k][r] + a[l]\cdot a[k]\cdot a[r]\big) \]

int maxCoins(vector<int>& nums) {
    int n = nums.size();
    vector<int> a(n + 2, 1);
    for (int i = 0; i < n; ++i) a[i + 1] = nums[i];
    vector<vector<int>> dp(n + 2, vector<int>(n + 2, 0));
    for (int len = 2; len <= n + 1; ++len)          // range length
        for (int l = 0; l + len <= n + 1; ++l) {
            int r = l + len;
            for (int k = l + 1; k < r; ++k)
                dp[l][r] = max(dp[l][r],
                    dp[l][k] + dp[k][r] + a[l] * a[k] * a[r]);
        }
    return dp[0][n + 1];
}

The trick that makes interval DP work here is choosing the last balloon to burst in the range, not the first. The last one sees only the boundaries, so the two sides become independent subproblems.

Matrix-chain multiplication, optimal BST, stone merging, and “remove boxes” all have this shape. Cost is \(O(n^3)\) states times splits, which is fine up to \(n \approx 500\).

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  c/.style={draw, thick, minimum size=0.5cm, font=\scriptsize}]
  \foreach \i in {0,...,4} \foreach \j in {0,...,4} {
    \ifnum\j>\i
      \node[c, fill=blue!8] at (\j*0.55,-\i*0.55) {};
    \else
      \node[c, fill=gray!5] at (\j*0.55,-\i*0.55) {};
    \fi
  }
  \node[font=\scriptsize, anchor=west] at (3.1,-0.65) {fill by increasing length};
  \draw[->, thick, orange] (0.55,-1.1) -- (1.1,-1.1);
  \node[font=\scriptsize, text=orange!80!black, anchor=north] at (0.82,-1.15) {len 2};
\end{tikzpicture}
QQuestionWhy iterate by range length rather than by l then r?
ASolution

dp[l][r] depends on dp[l][k] and dp[k][r], which are strictly shorter ranges. Length order is a topological order; a plain l-then-r scan reads uncomputed cells.

Tree DP

Tree DP is postorder recursion: children return summaries, the parent combines them. There is no cycle, so no visited array is needed — only the parent.

Binary tree maximum path sum. A path goes up through a node and down into at most two branches. The recursion returns the best downward gain, and the answer is updated with the best “through this node” path.

int best = INT_MIN;
int gain(TreeNode* n) {
    if (!n) return 0;
    int l = max(0, gain(n->left));       // a negative branch is not worth taking
    int r = max(0, gain(n->right));
    best = max(best, n->val + l + r);    // path through n
    return n->val + max(l, r);           // only one branch can go to the parent
}

Two different quantities are in play: the value returned to the parent (one branch) and the value recorded as an answer (two branches). Conflating them is the classic bug.

Child-to-parent propagation. For “sum of distances” or “subtree size”, each child adds its summary to the parent after its own recursion finishes:

void dfs(int u, int parent, const vector<vector<int>>& g, vector<int>& sub) {
    sub[u] = 1;
    for (int v : g[u]) {
        if (v == parent) continue;
        dfs(v, u, g, sub);
        sub[u] += sub[v];
    }
}

Rerooting DP (Ch. 5) is the second pass that turns “answer for the root” into “answer for every node” using the same summaries.

QQuestionWhy is a visited array unnecessary in tree DP?
ASolution

A tree has no cycles, so the only already-visited neighbour is the parent. Skipping the parent is enough to prevent backtracking.

DP on DAGs

Any DAG has a topological order, and DP over a DAG is one pass in that order. Shortest and longest paths, counting paths, and “number of ways to reach the end” are all the same loop.

vector<long long> longestPath(int n, const vector<vector<pair<int,int>>>& g,
                              const vector<int>& topo) {
    vector<long long> dp(n, 0);           // longest path ending at v
    for (int u : topo)
        for (auto [v, w] : g[u])
            dp[v] = max(dp[v], dp[u] + w);
    return dp;
}

This is Bellman–Ford’s job done in \(O(V+E)\) because the DAG order removes the need for repeated relaxation passes. It is also the reason “DP on a DAG” and “topological sort” are the same topic.

If the graph has cycles, the DP is invalid — a longest path in a cyclic graph can be unbounded, or requires SCC condensation first.

QQuestionWhy does DP on a DAG only need one pass, while Bellman–Ford needs

\(V-1\)?

ASolution

In topological order, every predecessor of v is finalized before v is processed. Without an order, one pass cannot guarantee that.

Bitmask DP

When the state is “which of n items are used” and n <= 20, the subset is a bitmask. There are \(2^n\) masks, and dp[mask] is computed from masks with one fewer bit.

Travelling salesman, \(O(2^n n^2)\):

int tsp(const vector<vector<int>>& cost) {
    int n = cost.size(), FULL = (1 << n) - 1;
    const int INF = 1e9;
    vector<vector<int>> dp(1 << n, vector<int>(n, INF));
    dp[1][0] = 0;                              // start at 0, only 0 visited
    for (int mask = 1; mask <= FULL; ++mask)
        for (int u = 0; u < n; ++u) {
            if (!(mask & (1 << u)) || dp[mask][u] == INF) continue;
            for (int v = 0; v < n; ++v) {
                if (mask & (1 << v)) continue;
                int next = mask | (1 << v);
                dp[next][v] = min(dp[next][v], dp[mask][u] + cost[u][v]);
            }
        }
    int best = INF;
    for (int u = 1; u < n; ++u)
        best = min(best, dp[FULL][u] + cost[u][0]);
    return best;
}

States rise in mask because next > mask numerically (adding a bit always increases the value), so the loop order is valid.

Subset enumeration for partitioning problems:

for (int sub = mask; sub; sub = (sub - 1) & mask) { /* proper non-empty subset */ }

Total work over all masks is \(O(3^n)\), which is why \(n \le 15\) is the practical limit.

QQuestionWhy does TSP’s mask loop work in increasing numeric order?
ASolution

Adding a bit always produces a larger integer, so every predecessor mask is strictly smaller. Increasing mask is a topological order of the subset lattice.

State compression

State compression means encoding a complex state — a profile of the previous row, a set, a count — into an integer index. It is how you fit a 2D state into 1D DP.

Domino tiling (2 × n board, 1 × 2 tiles): the state is a bitmask of which cells in the current column are already filled by horizontal tiles from the previous column.

int tileWays(int n) {                        // 2 x n board, 1 x 2 dominoes
    int S = 1 << 2;                          // mask of cells already covered
    vector<long long> dp(S, 0), ndp(S, 0);
    dp[0] = 1;
    for (int c = 0; c < n; ++c) {
        fill(ndp.begin(), ndp.end(), 0);
        for (int mask = 0; mask < S; ++mask) {
            long long ways = dp[mask];
            if (!ways) continue;
            if (mask == 0) {                 // both cells free
                ndp[0] += ways;              // one vertical domino
                ndp[3] += ways;              // two horizontals spilling right
            } else if (mask == 3) {          // both already covered
                ndp[0] += ways;
            } else if (mask == 1) {          // top covered, bottom free
                ndp[2] += ways;              // one horizontal on the bottom
            } else {                         // mask == 2
                ndp[1] += ways;
            }
        }
        dp.swap(ndp);
    }
    return (int)dp[0];                       // no tile may hang past the last column
}

The real version generates valid transitions once, then applies them to every mask. Complexity is \(O(n \cdot 2^H)\) instead of \(O(n \cdot 2^{2H})\).

Compression also covers:

QQuestionWhat does the bitmask in domino tiling actually represent?
ASolution

Which cells of the current column are already occupied by horizontal tiles sticking out from the previous column. It is a boundary state between columns.

When greedy does not work

Greedy picks the locally best option and never reconsiders. It is correct only when an exchange argument proves it. Two standard counterexamples:

Coin change. {1, 3, 4}, amount 6. Greedy: 4, 1, 1 (3 coins). Optimal: 3, 3 (2 coins). The locally largest coin is not part of the global optimum.

0/1 knapsack. Items (weight, value): (10, 60), (20, 100), (30, 120), capacity 50. Greedy by value/weight ratio takes the 10 and 20 (value 160); the optimal is 20 + 30 (value 220). Ratio order fails because items are indivisible.

A quick test for whether greedy is plausible: can you construct a case where taking the best-looking item blocks two slightly worse ones? If yes, DP.

The distinction in one line: greedy commits, DP explores. If the problem’s answer needs a choice that depends on future options, DP.

QQuestionCoin change with {1, 5, 10, 25} — why does greedy work there?
ASolution

It is a canonical coin system: every coin is at least twice the previous one, so the greedy choice can always be exchanged for the optimum. The guarantee comes from the denomination set, not from the problem shape.

The eleven-problem progression

Each row is the four answers you must be able to say out loud.

Problem State Transition Base Order
Climbing Stairs dp[i] ways to step i dp[i-1] + dp[i-2] dp[0]=dp[1]=1 i ascending
House Robber dp[i] best up to i max(dp[i-1], dp[i-2]+a[i]) dp[0]=a[0], dp[1]=max i ascending
Coin Change dp[x] min coins for x 1 + min(dp[x-c]) dp[0]=0, rest INF x ascending
Unique Paths dp[i][j] paths to cell dp[i-1][j] + dp[i][j-1] first row/col = 1 row-major
Minimum Path Sum dp[i][j] min cost grid + min(up, left) first row/col prefix sums row-major
LCS dp[i][j] on prefixes match ? diagonal+1 : max(up, left) row/col 0 both ascending
LIS dp[i] ending at i 1 + max(dp[j]) for a[j]<a[i] 1 i ascending
Edit Distance dp[i][j] prefixes match ? diagonal : 1+min(3) dp[i][0]=i, dp[0][j]=j both ascending
Partition Equal Subset dp[s] reachable dp[s] \|= dp[s-x] dp[0]=true s descending
Binary Tree Max Path gain per subtree val + max(l,r), answer val+l+r null = 0 postorder
Tree DP (subtree sum) sub[u] 1 + sum(sub[child]) leaf = 1 postorder

For each, practice saying the four sentences before writing code. That is the skill the OA tests, more than the syntax.

Bugs and edge cases

QQuestionA DP passes small cases and fails at n = 2000. What do you check?
ASolution

Overflow first (counts or sums need long long), then the complexity (is it accidentally \(O(n^3)\)?), then whether an INF value got used in arithmetic.

Next: Greedy Algorithms (DSA Core #8) — choice properties, exchange arguments, and the counterexamples that decide when DP is required.