Patterns: algorithm design
This algorithm design review teaches you to spot which idea a problem needs (backtracking to list every solution, greedy, divide and conquer, or dynamic programming when small problems repeat) and drills the two classic DPs: longest common subsequence with dp[i][j] and longest increasing subsequence.
This chapter's four ideas don't come with their names written on the problem. Take "making change": asking for the fewest coins is dynamic programming, asking to list every way is backtracking, and with coins of 25, 10, 5 and 1, greedy is enough. In interviews and exams, recognising which one fits is often harder than writing the code. This lesson has three patterns: recognising the problem first, then the two DPs asked most often.
Pattern one: recognise the idea first
- A problem → List every solution?
- List every solution? → Backtracking, with pruning (yes)
- List every solution? → Can "best at each step" be proved? (just the best value or a count)
- Can "best at each step" be proved? → Greedy (yes)
- Can "best at each step" be proved? → Do smaller problems repeat? (no proof, or a counterexample)
- Do smaller problems repeat? → Dynamic programming (yes)
- Do smaller problems repeat? → Divide and conquer (independent)
| The signal in the problem | Most likely | Examples |
|---|---|---|
| "List all", "print every way" | Backtracking | Permutations, subsets, N-queens, combination sum |
| "Most / fewest / how many ways", and a few small cases show repeated smaller problems | Dynamic programming | Knapsack, climbing stairs, LCS, edit distance |
| A natural sort order or "first pick the most …", and no counterexample turns up | Greedy | Interval scheduling, Huffman, fractional knapsack |
| It cuts in half, the halves don't affect each other, combining is easy | Divide and conquer | Merge sort, fast power, counting inversions |
| n up to about 20 | 2ⁿ and n! both run: backtracking | |
| n of 10⁵ or more | Only O(n log n) or less: greedy, binary search, 1D DP |
The input size is a strong hint: a problem with n at most 20 is the setter telling you to search everything; with n up to 10⁵, even O(n²) won't finish.
"n ≤ 15: print every subset that sums to k." Which idea fits?
"Coins of 1, 3 and 4: the fewest coins that make amount." Which idea fits?
The jump game (greedy)
✓You start at index 0, and a[i] is the furthest you can jump forward from index i. Can you reach the last index? Greedy: walk left to right keeping "the furthest reachable so far"; once the index you're at is past it, you can't get there.
1 0
1#include <stdio.h>2 3int can_jump(int a[], int n) {4 int far = 0;5 // i from 0 to n - 1: if i > far return 0; otherwise far = max(far, i + a[i])6 return 1;7}8 9int main(void) {10 int a[] = {2, 3, 1, 1, 4};11 int b[] = {3, 2, 1, 0, 4};12 printf("%d %d\n", can_jump(a, 5), can_jump(b, 5));13 return 0;14}
Pattern two: two strings, a 2D table
The longest common subsequence (LCS): the longest string you can get from both strings by deleting some characters (without reordering). The LCS of ABCB and BDCAB, for example, is BCB, length 3. A subsequence needn't be contiguous.
Nearly every DP on two strings is this table: dp[i][j] = the answer for the first i characters of s and the first j of t. Look at the last characters:
- s[i − 1] == t[j − 1]: that character can go in the common subsequence, dp[i][j] = dp[i − 1][j − 1] + 1 (up-left + 1);
- not equal: at least one of them can't be used, so drop s's or drop t's, dp[i][j] = max(dp[i − 1][j], dp[i][j − 1]) (the bigger of above and left).
Reading back works as in the knapsack, walking back from the bottom right: equal characters are noted and the walk goes up-left; unequal ones go toward the bigger of above and left (either one when they're equal).
1#include <stdio.h>2#include <string.h>3 4int dp[20][20];5 6int main(void) {7 const char *s = "ABCBDAB", *t = "BDCABA";8 int n = strlen(s), m = strlen(t);9 for (int i = 1; i <= n; i++)10 for (int j = 1; j <= m; j++)11 if (s[i - 1] == t[j - 1]) dp[i][j] = dp[i - 1][j - 1] + 1;12 else dp[i][j] = dp[i - 1][j] > dp[i][j - 1] ? dp[i - 1][j] : dp[i][j - 1];13 14 char out[20];15 int len = dp[n][m], i = n, j = m;16 out[len] = '\0';17 while (i > 0 && j > 0) { // reading back from the bottom right18 if (s[i - 1] == t[j - 1]) { out[--len] = s[i - 1]; i--; j--; }19 else if (dp[i - 1][j] >= dp[i][j - 1]) i--;20 else j--;21 }22 printf("LCS length %d: %s\n", dp[n][m], out);23 return 0;24}
LCS length 4: BCBA
The LCS of ABCBDAB and BDCABA has length 4, and there's more than one (BCBA, BDAB and BCAB all are); reading back with different choices gives different ones, always of the same length. Time and space are both O(nm). Edit distance (this stage's exercise) uses this same table, with one more choice per box.
Work out one box yourself: s = ACB, t = ABCB, with most of the table filled in already.
What goes in the question-mark box, dp[3][3] (the LCS length of "ACB" and "ABC")?
Longest common substring
✓Unlike a subsequence, a substring must be contiguous. dp[i][j] becomes "the length of the common substring ending at s[i − 1] and t[j − 1]": equal means up-left + 1, unequal breaks it, 0. The answer is the biggest in the table.
4 3
1#include <stdio.h>2#include <string.h>3 4int longest(const char *s, const char *t) {5 int dp[20][20] = {{0}}, best = 0;6 int n = strlen(s), m = strlen(t);7 // i from 1 to n, j from 1 to m: equal gives dp[i][j] = dp[i - 1][j - 1] + 1, and update best; unequal is 08 return best;9}10 11int main(void) {12 printf("%d %d\n", longest("ABABC", "BABCA"), longest("abcdef", "zcdemf"));13 return 0;14}
Edit distance
✓Turn s into t, one character inserted, deleted or replaced per step: how few steps? dp[i][j] is the fewest steps turning the first i of s into the first j of t. Row 0 and column 0 are filled in already (all inserts, all deletes). Equal: dp[i − 1][j − 1]; unequal: 1 + the smallest of three (delete: above, insert: left, replace: up-left).
3 5
1#include <stdio.h>2#include <string.h>3 4int min3(int a, int b, int c) { int m = a < b ? a : b; return m < c ? m : c; }5 6int edit(const char *s, const char *t) {7 int dp[20][20];8 int n = strlen(s), m = strlen(t);9 for (int i = 0; i <= n; i++) dp[i][0] = i;10 for (int j = 0; j <= m; j++) dp[0][j] = j;11 // i from 1 to n, j from 1 to m: fill in dp[i][j]12 return dp[n][m];13}14 15int main(void) {16 printf("%d %d\n", edit("horse", "ros"), edit("intention", "execution"));17 return 0;18}
Pattern three: one sequence, dp[i] ending at item i
The longest increasing subsequence (LIS): in 10 9 2 5 3 7 101 18, how long is the longest strictly increasing subsequence (not necessarily contiguous)? 4, for example 2 3 7 18.
For DP on one sequence, the most common state is dp[i] = the answer ending at a[i]. An increasing subsequence ending at a[i] has, just before it, some j < i with a[j] < a[i], and it extends the longest one ending at a[j]:
dp[i] = 1 + max{ dp[j] : j < i and a[j] < a[i] } (1 if there's no such j). The answer is the largest dp[i] of all, not necessarily dp[n − 1].
1#include <stdio.h>2 3int main(void) {4 int a[] = {10, 9, 2, 5, 3, 7, 101, 18};5 int n = 8, dp[8], best = 0;6 for (int i = 0; i < n; i++) {7 dp[i] = 1; // just itself8 for (int j = 0; j < i; j++) // after some smaller one9 if (a[j] < a[i] && dp[j] + 1 > dp[i]) dp[i] = dp[j] + 1;10 if (dp[i] > best) best = dp[i];11 }12 for (int i = 0; i < n; i++) printf("%d ", dp[i]);13 printf("\nlongest increasing subsequence: %d\n", best);14 return 0;15}
1 1 1 2 2 3 4 4 longest increasing subsequence: 4
Two nested loops: O(n²). There's also an O(n log n) way: keep an array of "the smallest end of an increasing subsequence of length k"; it's sorted, so each new number finds its place with chapter 6's binary search and replaces what's there.
| Problem | State | Transition | Time |
|---|---|---|---|
| Longest common subsequence | dp[i][j]: the first i and the first j | Equal: up-left + 1; else max(above, left) | O(nm) |
| Edit distance | dp[i][j]: fewest steps turning the first i into the first j | Equal: up-left; else 1 + min(above, left, up-left) | O(nm) |
| Longest increasing subsequence | dp[i]: ending at a[i] | 1 + max(dp[j]), a[j] < a[i] | O(n²) |
| Maximum subarray sum | dp[i]: ending at a[i] | max(a[i], dp[i − 1] + a[i]) | O(n) |
In exams: algorithm design questions ask you to "give the idea, write the code, state the complexity": a sentence or two that makes the state and the transition clear earns more than the code. LCS, LIS, edit distance and the knapsack are the four DPs asked most, in interviews too. "Subsequence" suggests LCS or LIS; "turning one string into another" suggests edit distance.
a = 3 1 4 1 5 9 2 6, and dp[i] is the length of the longest strictly increasing subsequence ending at a[i]. Which is the dp array?
Maximum subarray sum (one unbroken stretch with the biggest sum): dp[i] is the biggest sum ending at a[i], kept in a single rolling variable cur. What does it print?
1#include <stdio.h>2 3int main(void) {4 int a[] = {-2, 1, -3, 4, -1, 2, 1, -5, 4};5 int cur = a[0], best = a[0];6 for (int i = 1; i < 9; i++) {7 cur = cur + a[i] > a[i] ? cur + a[i] : a[i];8 if (cur > best) best = cur;9 }10 printf("%d\n", best);11 return 0;12}
Summary
Three patterns of algorithm design
- Recognise it: list all → backtracking; best step provable → greedy; repeats → DP; independent → divide and conquer
- Two strings: dp[i][j] for the first i and first j; equal looks up-left, unequal above and left
- One sequence: dp[i] ends at a[i], and the answer is the biggest dp of all
- Check the input size first: n ≤ 20 can search, n ≥ 10⁵ needs O(n log n)
1for (int i = 1; i <= n; i++)2 for (int j = 1; j <= m; j++)3 dp[i][j] = s[i - 1] == t[j - 1] ? dp[i - 1][j - 1] + 14 : max(dp[i - 1][j], dp[i][j - 1]);
Chapter 8 quick check
5 questions: fast power's calls, counting combinations by backtracking, a counterexample to greedy, paths through a grid, and a knapsack with its loop the wrong way round. Work out what it prints first, then pick.
How many calls to power does power(1, 100) make in all?
1#include <stdio.h>2 3int calls = 0;4 5long long power(long long x, int n) {6 calls++;7 if (n == 0) return 1;8 long long h = power(x, n / 2);9 h = h * h;10 if (n % 2 == 1) h = h * x;11 return h;12}13 14int main(void) {15 power(1, 100);16 printf("%d\n", calls);17 return 0;18}
Choosing 3 of 1 to 5 (only moving forward), how many ways does the backtracking count?
1#include <stdio.h>2 3int count = 0, n = 5, k = 3, len = 0;4 5void dfs(int start) {6 if (len == k) {7 count++;8 return;9 }10 for (int i = start; i <= n; i++) {11 len++;12 dfs(i + 1);13 len--;14 }15}16 17int main(void) {18 dfs(1);19 printf("%d\n", count);20 return 0;21}
With coins of 10, 7 and 1, how many coins does greedy use for 14?
1#include <stdio.h>2 3int main(void) {4 int coins[] = {10, 7, 1};5 int amount = 14, count = 0;6 for (int i = 0; i < 3; i++)7 while (amount >= coins[i]) {8 amount -= coins[i];9 count++;10 }11 printf("%d\n", count);12 return 0;13}
A grid of 3 rows and 4 columns, from the top left to the bottom right, moving only right or down at each step: how many paths?
1#include <stdio.h>2 3int main(void) {4 int dp[3][4];5 for (int i = 0; i < 3; i++)6 for (int j = 0; j < 4; j++)7 if (i == 0 || j == 0) dp[i][j] = 1;8 else dp[i][j] = dp[i - 1][j] + dp[i][j - 1];9 printf("%d\n", dp[2][3]);10 return 0;11}
It was meant to be a 0-1 knapsack (capacity 7, one of each of two items), but the inner loop runs forwards. What does it print?
1#include <stdio.h>2 3int main(void) {4 int w[] = {2, 3};5 int v[] = {3, 5};6 int dp[8] = {0};7 for (int i = 0; i < 2; i++)8 for (int j = w[i]; j <= 7; j++)9 if (dp[j - w[i]] + v[i] > dp[j])10 dp[j] = dp[j - w[i]] + v[i];11 printf("%d\n", dp[7]);12 return 0;13}