Patterns: algorithm design
This chapter 8 review works through three classic problems: the longest common subsequence and the edit distance of two strings, each filled in as one dp[i][j] table, and N-queens, backtracking with three sets that finds all 92 solutions for 8 queens.
This chapter covered four ideas: divide and conquer, backtracking, greedy algorithms and dynamic programming. Faced with a problem, ask three questions. Must every possibility be listed? Then it is backtracking, and look for pruning. Can "the best at each step" be proved? Then it is greedy, but look for a counterexample first. Do small problems repeat? If so, dynamic programming; if not, divide and conquer. The "big" interview problems asked most often use exactly these to the full: the longest common subsequence and edit distance of two strings (behind git diff, spelling correction, DNA alignment) are the same kind of 2D table; N-queens is the standard backtracking-with-pruning problem. This lesson makes the three patterns second nature.
First, tell which idea it is
- 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?
Pattern 1: two strings, one 2D table
The longest common subsequence (LCS): a subsequence picks some characters of a string in order (not necessarily next to each other); "BCB" is a subsequence of "ABCB". How long is the longest subsequence that two strings share?
For two-string problems, the state is nearly always dp[i][j] = the answer for the first i characters of a and the first j characters of b. The transition looks only at the last characters:
a[i-1] == b[j-1]: this character can certainly go into the common subsequence,dp[i][j] = dp[i-1][j-1] + 1(top-left + 1);- not equal: at least one of them is unused, so drop a's last or b's last,
dp[i][j] = max(dp[i-1][j], dp[i][j-1])(the larger of above and left).
Row 0 and column 0 are the empty string, whose common subsequence with anything is 0.
1def lcs(a, b):2 n, m = len(a), len(b)3 dp = [[0] * (m + 1) for _ in range(n + 1)]4 for i in range(1, n + 1):5 for j in range(1, m + 1):6 if a[i - 1] == b[j - 1]:7 dp[i][j] = dp[i - 1][j - 1] + 1 # top-left + 18 else:9 dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]) # the larger of above and left10 out = []11 i, j = n, m12 while i > 0 and j > 0: # walk back from the bottom-right13 if a[i - 1] == b[j - 1]:14 out.append(a[i - 1])15 i -= 116 j -= 117 elif dp[i - 1][j] >= dp[i][j - 1]:18 i -= 119 else:20 j -= 121 return dp[n][m], "".join(reversed(out))22 23print(lcs("ABCB", "BDCAB"))24print(lcs("abcde", "ace"))25print(lcs("python", "java"))
(3, 'BCB') (3, 'ace') (0, '')
Time and space are both O(n × m). Walking back collects out backwards, hence the reversed at the end. When above and left are equal, either way is right; you may just read off another subsequence of the same length: the longest length is unique, but there can be several subsequences that long.
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")?
The length of the longest common subsequence
✓Complete lcs_len(a, b): return the length of the longest common subsequence of a and b. dp[i][j] is the answer for the first i and the first j.
3 0 4 0
1def lcs_len(a, b):2 n, m = len(a), len(b)3 dp = [[0] * (m + 1) for _ in range(n + 1)]4 # i from 1 to n, j from 1 to m: equal takes top-left + 1, unequal the larger of above and left5 return dp[n][m]6 7print(lcs_len("abcde", "ace"))8print(lcs_len("abc", "def"))9print(lcs_len("AGGTAB", "GXTXAYB"), lcs_len("", "abc"))
Pattern 2: edit distance, the cheapest of three edits
Edit distance: to turn string a into b, each step inserts, deletes or replaces one character. How few steps will do? "horse" → "ros" takes 3: replace h with r (rorse), delete r (rose), delete e (ros).
Again dp[i][j] = the fewest steps turning a's first i into b's first j, and again look at the last characters:
- equal: the last one needs no edit,
dp[i][j] = dp[i-1][j-1]; - unequal: the cheapest of three, plus 1: replace (top-left
dp[i-1][j-1]), delete a's last (above,dp[i-1][j]), insert b's last (left,dp[i][j-1]). - Base cases: row 0
dp[0][j] = j(insert j into an empty string), column 0dp[i][0] = i(delete i).
1def edit_distance(a, b):2 n, m = len(a), len(b)3 dp = [[0] * (m + 1) for _ in range(n + 1)]4 for i in range(n + 1):5 dp[i][0] = i # delete i6 for j in range(m + 1):7 dp[0][j] = j # insert j8 for i in range(1, n + 1):9 for j in range(1, m + 1):10 if a[i - 1] == b[j - 1]:11 dp[i][j] = dp[i - 1][j - 1]12 else:13 dp[i][j] = 1 + min(dp[i - 1][j - 1], # replace14 dp[i - 1][j], # delete15 dp[i][j - 1]) # insert16 return dp17 18dp = edit_distance("horse", "ros")19for row in dp:20 print(row)21print(edit_distance("intention", "execution")[-1][-1])22print(edit_distance("kitten", "sitting")[-1][-1], edit_distance("", "abc")[-1][-1])
[0, 1, 2, 3] [1, 1, 2, 3] [2, 2, 1, 2] [3, 2, 2, 2] [4, 3, 3, 2] [5, 4, 4, 3] 5 3 3
| Problem | dp[i][j] | Last characters equal | Unequal |
|---|---|---|---|
| Longest common subsequence | the longest for the first i and first j | top-left + 1 | max(above, left) |
| Edit distance | the fewest edits from the first i to the first j | top-left | 1 + min(top-left, above, left) |
| Longest common substring (contiguous) | the longest ending at a[i-1] and b[j-1] | top-left + 1 | 0 |
For two-string problems, only the two sentences "when equal" and "when unequal" change. When a row depends only on the row above, it can roll into one list, like the knapsack.
Edit distance: what is the fewest steps to turn "abc" into "yabd" (inserting, deleting or replacing one character is one step each)?
Edit distance
✓Complete edit(a, b): the fewest inserts, deletes or replacements that turn a into b. Fill row 0 and column 0 first.
3 5 0 2 2
1def edit(a, b):2 n, m = len(a), len(b)3 dp = [[0] * (m + 1) for _ in range(n + 1)]4 # column 0 is i, row 0 is j5 # the rest: equal copies the top-left; unequal is 1 + min(top-left, above, left)6 return dp[n][m]7 8print(edit("horse", "ros"))9print(edit("intention", "execution"))10print(edit("abc", "abc"), edit("", "ab"), edit("ab", ""))
Pattern 3: N-queens, backtracking with three sets
Place n queens on an n × n board so that no two share a row, a column or a diagonal. How many ways are there?
Each row holds exactly one queen, so place them row by row: in row r, try each column c; if it is safe, place it, recurse into the next row, then pick it up again (backtracking's choose, explore, un-choose). The key is a fast safety test, with three sets of what is attacked:
cols: the columns c that are taken;diag: the taken "↘ diagonals", wherer - cis the same all along the line;anti: the taken "↙ diagonals", wherer + cis the same all along the line.
All three in tests are O(1), faster than scanning back over the queens already placed. A square under attack is never entered: that is the pruning.
1def go(r):2 nonlocal nodes3 nodes += 14 if r == n: # all n rows placed5 res.append(path[:])6 return7 for c in range(n):8 if c in cols or r - c in diag or r + c in anti:9 continue # attacked: pruned10 cols.add(c); diag.add(r - c); anti.add(r + c); path.append(c)11 go(r + 1)12 cols.remove(c); diag.remove(r - c); anti.remove(r + c); path.pop()
1from itertools import permutations2 3def solve_queens(n):4 cols, diag, anti = set(), set(), set()5 res, path = [], []6 nodes = 07 8 def go(r):9 nonlocal nodes10 nodes += 111 if r == n: # all n rows placed12 res.append(path[:])13 return14 for c in range(n):15 if c in cols or r - c in diag or r + c in anti:16 continue # attacked: pruned17 cols.add(c); diag.add(r - c); anti.add(r + c); path.append(c)18 go(r + 1)19 cols.remove(c); diag.remove(r - c); anti.remove(r + c); path.pop()20 21 go(0)22 return res, nodes23 24for n in [4, 5, 6, 8]:25 res, nodes = solve_queens(n)26 print(f"{n} queens: {len(res)} solutions, {nodes} nodes, the first {res[0]}")27 28def brute(n): # one per row, all columns different: try every permutation29 count = tried = 030 for p in permutations(range(n)):31 tried += 132 if len({r - p[r] for r in range(n)}) == n and len({r + p[r] for r in range(n)}) == n:33 count += 134 return count, tried35 36print("6 queens, every permutation:", brute(6))
4 queens: 2 solutions, 17 nodes, the first [1, 3, 0, 2] 5 queens: 10 solutions, 54 nodes, the first [0, 2, 4, 1, 3] 6 queens: 4 solutions, 153 nodes, the first [1, 3, 5, 0, 2, 4] 8 queens: 92 solutions, 2057 nodes, the first [0, 4, 7, 5, 2, 6, 1, 3] 6 queens, every permutation: (4, 720)
All 92 solutions of 8-queens take only 2057 nodes of backtracking; even a brute force clever enough to try only "one per column" permutations has 8! = 40320 to try for 8-queens. The earlier the cut, the more it saves: a dead end spotted in row 2 removes the whole subtree beneath it.
In interviews: first say which idea fits and why: "every solution is wanted, so backtracking; safety is three set lookups, O(1)"; "two strings, so dp[i][j] means the first i and the first j, and look at the last characters". Say what the state means and half the code is written. The follow-ups you will hear most: why the diagonals are r − c and r + c; how to output the LCS itself (walk back); which edit each of edit distance's three directions stands for.
What is the same for every square on one "↙" diagonal? Fill in the blank so the program prints how many solutions 4 to 8 queens have.
1def count_queens(n):2 cols, diag, anti = set(), set(), set()3 res = 04 5 def go(r):6 nonlocal res7 if r == n:8 res += 19 return10 for c in range(n):11 if c in cols or r - c in diag or in anti:12 continue13 cols.add(c); diag.add(r - c); anti.add(r + c)14 go(r + 1)15 cols.remove(c); diag.remove(r - c); anti.remove(r + c)16 17 go(0)18 return res19 20print([count_queens(n) for n in range(4, 9)])
r + c stays the same: that is what anti records. r - c would just repeat diag, leaving the "↙" lines unguarded; c repeats cols; r never clashes anyway (one queen per row) and doesn't guard the diagonal either. All three count far too many "solutions".Laying out N queens
✓Complete queens(n): return every solution, each as n strings where string r has Q in its queen's column and . everywhere else. Search with row 0's column from smallest up, and test safety with three sets.
['.Q..', '...Q', 'Q...', '..Q.'] ['..Q.', 'Q...', '...Q', '.Q..'] 4 1 0
1def queens(n):2 cols, diag, anti = set(), set(), set()3 res, path = [], []4 5 def go(r):6 if r == n:7 res.append(["." * c + "Q" + "." * (n - c - 1) for c in path])8 return9 # in row r try each column c: skip it if cols, diag (r - c) or anti (r + c) blocks it10 # otherwise add to all three sets, path.append(c), go(r + 1), then undo everything11 pass12 13 go(0)14 return res15 16for board in queens(4):17 print(board)18print(len(queens(6)), len(queens(1)), len(queens(3)))
How you write it at work
A 2D DP can also be written as "recursion + @lru_cache": the state (i, j) is one box of the table; copy the transition and stop worrying about the order of filling:
1from functools import lru_cache2 3def lcs_len(a, b):4 @lru_cache(maxsize=None)5 def go(i, j): # the LCS length of a[i:] and b[j:]6 if i == len(a) or j == len(b):7 return 08 if a[i] == b[j]:9 return go(i + 1, j + 1) + 110 return max(go(i + 1, j), go(i, j + 1))11 result = go(0, 0)12 return result, go.cache_info()13 14print(lcs_len("ABCB", "BDCAB"))15print(lcs_len("abcde", "ace"))
(3, CacheInfo(hits=8, misses=22, maxsize=None, currsize=22)) (3, CacheInfo(hits=1, misses=11, maxsize=None, currsize=11))
- The cached function lives inside, and
a,bare not arguments: only the two indexes are, so each cache key is one box of the table. Every call oflcs_lengets a fresh cache, so different strings never mix. - The recursion goes up to
len(a) + len(b)deep; with strings in the thousands that is aRecursionError, and then the table filled by loops, as in patterns 1 and 2, is the answer. - To actually compare two texts and find what changed, the standard library has
difflib(SequenceMatcher,unified_diff), built on similar ideas and formatting the result as a diff. - Problems like N-queens that want "every solution" have no ready-made library;
itertools.permutationscan guarantee "one per column", but it never prunes, and for slightly larger n it is far slower than hand-written backtracking.
LCS with memoization. What does it print?
1from functools import lru_cache2 3def lcs_len(a, b):4 @lru_cache(maxsize=None)5 def go(i, j):6 if i == len(a) or j == len(b):7 return 08 if a[i] == b[j]:9 return go(i + 1, j + 1) + 110 return max(go(i + 1, j), go(i, j + 1))11 return go(0, 0)12 13print(lcs_len("ABC", "CAB"), lcs_len("ABC", ""))
j == len(b) holds straight away, so it returns 0.Summary
Three patterns of algorithm design
- Name the idea first: every answer, backtracking; provably best each step, greedy; repeated subproblems, DP; independent ones, divide and conquer
- Two strings: dp[i][j] is the first i and the first j; only the last characters matter
- LCS: equal top-left + 1, unequal max(above, left); edit distance: unequal 1 + min(top-left, above, left)
- Walk the arrows back to read off the answer; N-queens prunes in O(1) with three sets (c, r − c, r + c)
1if a[i - 1] == b[j - 1]:2 dp[i][j] = dp[i - 1][j - 1] + 13else:4 dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])5if c in cols or r - c in diag or r + c in anti: continue
Chapter 8 quick check
Five questions: fast power, copying in backtracking, greedy meetings, a memoised cache, and the direction of a one-list knapsack. Work out what each prints before you pick.
Fast power for 2 to the 10th. What does it print?
1calls = 02 3def power(x, n):4 global calls5 calls += 16 if n == 0:7 return 18 half = power(x, n // 2)9 return half * half * (x if n % 2 else 1)10 11print(power(2, 10), calls)
power(x, n // 2) twice and they become O(n).Each number is first "taken", then "left", generating the subsets of [0, 1, 2]. What does it print?
1res, path = [], []2 3def go(i):4 if i == 3:5 res.append(path[:])6 return7 path.append(i)8 go(i + 1)9 path.pop()10 go(i + 1)11 12go(0)13print(len(res), res[1])
path[:] each is its own list; with res.append(path) all 8 would be empty.Greedy by end time: which meetings does it schedule?
1meetings = [(1, 3), (2, 4), (3, 5), (0, 6), (5, 7)]2chosen, end = [], 03for s, e in sorted(meetings, key=lambda m: m[1]):4 if s >= end:5 chosen.append((s, e))6 end = e7print(chosen)
Grid paths, with a cache. What does it print?
1from functools import lru_cache2 3@lru_cache(maxsize=None)4def paths(i, j):5 if i == 0 or j == 0:6 return 17 return paths(i - 1, j) + paths(i, j - 1)8 9print(paths(2, 2), paths.cache_info())
One item (weight 2, value 3), a one-list knapsack with the inner loop going forwards. What does it print?
1dp = [0] * 52for w, v in [(2, 3)]:3 for c in range(w, 5):4 dp[c] = max(dp[c], dp[c - w] + v)5print(dp)
dp[4] = dp[2] + 3 reads a dp[2] that already holds this item, so capacity 4 holds it twice: 6. That is the unbounded knapsack (each item any number of times). The 0-1 knapsack goes backwards and gets [0, 0, 3, 3, 3].