Kodewick
Start learning →
Patterns: algorithm design52 / 52

Patterns: algorithm design

Lesson 52 of 52 · Part 9 · Algorithm design · about 26 minutes

This review of algorithm design teaches you to spot which idea a problem needs: all solutions (backtracking), the best choice at each step (greedy), independent parts (divide and conquer) or repeating subproblems (dynamic programming), plus longest common and longest increasing subsequences.

The four ideas of this chapter don't come with their names on the problem. Take "making change": the fewest coins is dynamic programming, listing every way is backtracking, and with coins 25, 10, 5 and 1 greedy is enough. In interviews and exams, recognising which one it is is often harder than writing the code. Three patterns below: recognise the problem first, then the two DPs asked most often.

Pattern 1: recognise the idea first

A problem
List every solution?
Backtracking, with pruning
Can "best at each step" be proved?
Greedy
Do smaller problems repeat?
Dynamic programming
Divide and conquer
yesjust the best value or a countyesno proof, or a counterexampleyesindependent
  • 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)
Given a problem, ask yourself these in this order
The signal in the problemUsuallyExamples
"List all", "print every one"BacktrackingPermutations, subsets, N queens, combination sum
"The most / the fewest / how many ways", and small cases show repeating subproblemsDynamic programmingKnapsack, climbing stairs, LCS, edit distance
A natural sort order or "take the most … first", and no counterexample turns upGreedyInterval scheduling, Huffman, fractional knapsack
Splits in half, the halves don't affect each other, and combining is easyDivide and conquerMerge sort, fast power, counting inversions
n up to about 202ⁿ and n! still run: backtracking
n of 10⁵ or moreO(n log n) at most: greedy, binary search, 1D DP

The input range is a strong hint: when n is at most 20, the setter wants you to search everything; when n reaches 10⁵, even O(n²) won't finish.

Choose one

"n ≤ 15: print every subset that sums to k." Which idea fits?

Exercise 1

The jump game (greedy)

You stand at index 0, and a[i] is how far at most 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.

It should print
1 0
exercise1.cpp
1#include <iostream>2#include <vector>3#include <algorithm>4using namespace std;5 6bool can_jump(const vector<int>& a) {7    int far = 0;8    // i from 0 to a.size() - 1: if i > far, return false; otherwise far = max(far, i + a[i])9    return true;10}11 12int main() {13    cout << can_jump({2, 3, 1, 1, 4}) << " " << can_jump({3, 2, 1, 0, 4}) << "\n";14    return 0;15}
Output
Press Run or Ctrl+Enter

Pattern 2: two strings, a 2D table

The longest common subsequence (LCS): the longest string that both strings can become by deleting some characters (without reordering). For ABCB and BDCAB it is BCB, length 3. A subsequence needn't be contiguous.

Nearly every DP on two strings uses 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]: this character can join the common subsequence, dp[i][j] = dp[i − 1][j − 1] + 1 (up-left + 1);
  • not equal: at least one of them is no use; 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).
∅BDCAB∅000000A0     B0     C0     B0     

LCS("ABCB", "BDCAB"): equal characters take up-left + 1, unequal ones the bigger of above and left

Reading back works as in the knapsack, from the bottom-right: when the characters are equal, note it and go up-left; when not, go toward the bigger box of above and left (either one if they tie). The characters come out last first, so reverse turns them round at the end.

main.cpp
1#include <iostream>2#include <vector>3#include <string>4#include <algorithm>5using namespace std;6 7int main() {8    string s = "ABCBDAB", t = "BDCABA";9    int n = s.size(), m = t.size();10    vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0));11    for (int i = 1; i <= n; i++)12        for (int j = 1; j <= m; j++)13            if (s[i - 1] == t[j - 1]) dp[i][j] = dp[i - 1][j - 1] + 1;14            else dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);15 16    string out;17    int i = n, j = m;18    while (i > 0 && j > 0) {                      // read back from the bottom-right19        if (s[i - 1] == t[j - 1]) { out += s[i - 1]; i--; j--; }20        else if (dp[i - 1][j] >= dp[i][j - 1]) i--;21        else j--;22    }23    reverse(out.begin(), out.end());              // collected backwards: turn it round24    cout << "LCS length " << dp[n][m] << ": " << out << "\n";25    return 0;26}
Output
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); read back in different directions and you get a different one, always of the same length. Time and space are both O(nm). Edit distance (exercise 3) uses the 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.

∅ABCB∅00000A01111C01122B012? 
LCS("ACB", "ABCB"): the question mark is dp[3][3], comparing s's 3rd character B with t's 3rd character C
Choose one

What goes in the question-mark box, dp[3][3] (the LCS length of "ACB" and "ABC")?

Exercise 2

Longest common substring

Unlike a subsequence, a substring must be contiguous. Make dp[i][j] "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.

It should print
4 3
exercise2.cpp
1#include <iostream>2#include <vector>3#include <string>4#include <algorithm>5using namespace std;6 7int longest(const string& s, const string& t) {8    int n = s.size(), m = t.size(), best = 0;9    vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0));10    // i from 1 to n, j from 1 to m: if equal, dp[i][j] = dp[i - 1][j - 1] + 1 and update best; else 011    return best;12}13 14int main() {15    cout << longest("ABABC", "BABCA") << " " << longest("abcdef", "zcdemf") << "\n";16    return 0;17}
Output
Press Run or Ctrl+Enter
Exercise 3

Edit distance

Turn s into t, inserting, deleting or replacing one character per step. What is the fewest 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 already filled (all inserts, all deletes). Equal: dp[i − 1][j − 1]; not equal: 1 + the smallest of three (delete: above, insert: left, replace: up-left).

It should print
3 5
exercise3.cpp
1#include <iostream>2#include <vector>3#include <string>4#include <algorithm>5using namespace std;6 7int edit(const string& s, const string& t) {8    int n = s.size(), m = t.size();9    vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0));10    for (int i = 0; i <= n; i++) dp[i][0] = i;11    for (int j = 0; j <= m; j++) dp[0][j] = j;12    // i from 1 to n, j from 1 to m: fill in dp[i][j]13    return dp[n][m];14}15 16int main() {17    cout << edit("horse", "ros") << " " << edit("intention", "execution") << "\n";18    return 0;19}
Output
Press Run or Ctrl+Enter

Pattern 3: 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 a DP on one sequence, the usual state is dp[i] = the answer ending at a[i]. An increasing subsequence ending at a[i] has, before a[i], 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 is no such j). The answer is the biggest of all the dp[i], not necessarily dp[n − 1].

01234567a[i]109253710118dp[i]        

LIS: row 2 is the length of the longest increasing subsequence ending at that column; each box looks at every smaller number to its left
main.cpp
1#include <iostream>2#include <vector>3#include <algorithm>4using namespace std;5 6int main() {7    vector<int> a = {10, 9, 2, 5, 3, 7, 101, 18};8    int n = a.size();9    vector<int> dp(n, 1);                         // just itself: 110    for (int i = 0; i < n; i++)11        for (int j = 0; j < i; j++)               // extend some smaller one before it12            if (a[j] < a[i]) dp[i] = max(dp[i], dp[j] + 1);13    for (int x : dp) cout << x << " ";14    cout << "\nLongest increasing subsequence: " << *max_element(dp.begin(), dp.end()) << "\n";15    return 0;16}
Output
1 1 1 2 2 3 4 4 
Longest increasing subsequence: 4

Two nested loops, O(n²). The answer is *max_element(dp.begin(), dp.end()), not dp.back(). There's also an O(n log n) way, shown in the STL stage.

ProblemStateTransitionTime
Longest common subsequencedp[i][j]: first i and first jEqual: up-left + 1; else max(above, left)O(nm)
Edit distancedp[i][j]: fewest steps turning first i into first jEqual: up-left; else 1 + min(above, left, up-left)O(nm)
Longest increasing subsequencedp[i]: ending at a[i]1 + max(dp[j]), a[j] < a[i]O(n²)
Maximum subarray sumdp[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.

Choose one

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?

Guess the outputA wrong guess is fine

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 <iostream>2#include <vector>3#include <algorithm>4using namespace std;5 6int main() {7    vector<int> a = {-2, 1, -3, 4, -1, 2, 1, -5, 4};8    int cur = a[0], best = a[0];9    for (int i = 1; i < (int)a.size(); i++) {10        cur = max(cur + a[i], a[i]);11        best = max(best, cur);12    }13    cout << best << "\n";14    return 0;15}

With the STL

Each of the four ideas has its handy tools in C++:

IdeaThe STL you reach forWatch out
Recursion / divide and conquerThe function itself, vectors passed as const vector<int>&Passing a vector by value copies it at every level
Backtrackingvector<int> path: push_back to choose, pop_back to undo; next_permutationWhatever you change going in, change back coming out
Greedysort with a comparator, priority_queueLook for a counterexample before writing code
Dynamic programmingvector<long long> dp(n + 1), vector<vector<int>>, max / min, an unordered_map memoAsk "is it there?" with find / count, not []

LIS in O(n log n): keep an array tail, where tail[k] is "the smallest possible last element of an increasing subsequence of length k + 1". It's always sorted. For each new number x, lower_bound finds the first position ≥ x: if there's none, append x (the longest got 1 longer); otherwise replace it with x (same length, smaller last element, easier to extend later). The length of tail is the answer.

main.cpp
1#include <iostream>2#include <vector>3#include <algorithm>4using namespace std;5 6int main() {7    vector<int> a = {10, 9, 2, 5, 3, 7, 101, 18};8    vector<int> tail;9    for (int x : a) {10        auto it = lower_bound(tail.begin(), tail.end(), x);   // first >= x11        if (it == tail.end()) tail.push_back(x);              // bigger than all: append12        else *it = x;                                         // a smaller last element13        cout << x << ": ";14        for (int y : tail) cout << y << " ";15        cout << "\n";16    }17    cout << "Longest increasing subsequence: " << tail.size() << "\n";18    return 0;19}
Output
10: 10 
9: 9 
2: 2 
5: 2 5 
3: 2 3 
7: 2 3 7 
101: 2 3 7 101 
18: 2 3 7 18 
Longest increasing subsequence: 4

Note that tail isn't necessarily a real increasing subsequence (here it ends as 2 3 7 18, which happens to be one; with other data it isn't); only its length is right.

Memoization with unordered_map: when the state has two parameters and you don't want the whole 2D table, join the two numbers into one key, say i * 1000 + j (with j below 1000). Here is LCS top-down, working out only the boxes that are actually asked for:

main.cpp
1#include <iostream>2#include <string>3#include <unordered_map>4#include <algorithm>5using namespace std;6 7string s = "ABCBDAB", t = "BDCABA";8unordered_map<long long, int> memo;              // key: i * 1000 + j9 10int lcs(int i, int j) {                          // the first i of s and the first j of t11    if (i == 0 || j == 0) return 0;12    long long key = (long long)i * 1000 + j;13    auto it = memo.find(key);14    if (it != memo.end()) return it->second;15    int r;16    if (s[i - 1] == t[j - 1]) r = lcs(i - 1, j - 1) + 1;17    else r = max(lcs(i - 1, j), lcs(i, j - 1));18    memo[key] = r;19    return r;20}21 22int main() {23    cout << "LCS length " << lcs(s.size(), t.size()) << "\n";24    cout << "The memo holds " << memo.size() << " states; the whole table has " << s.size() * t.size() << " boxes\n";25    cout << "lcs(4, 5) = " << memo.at(4 * 1000 + 5) << "\n";   // to see one state, look up its key26    return 0;27}
Output
LCS length 4
The memo holds 25 states; the whole table has 42 boxes
lcs(4, 5) = 3

An unordered_map is a hash table, O(1) per lookup on average, but its iteration order isn't fixed: another compiler or another amount of data, and for (auto& p : memo) may print in a different order. To print, look up each key (memo.at(key) throws if it's missing, instead of quietly inserting as [] does), or copy it into a vector and sort it. A pair<int, int> can't be an unordered_map key as is (there is no default hash for it), which is why the two are joined into one integer here; map<pair<int, int>, int> works too, at O(log m) per lookup.

In interviews: Say the idea before the code: which idea this is and why (every solution wanted? a counterexample to greedy? do subproblems repeat?), what the state and transition are, and the complexity. LCS, LIS, edit distance and knapsack are the four DPs asked most; LIS often gets the follow-up "O(n log n)?", answered with lower_bound on tail. "Subsequence" suggests LCS / LIS, "turning one string into another" suggests edit distance. Exam algorithm questions also ask you to "give the design idea, write the code, state the complexity": a sentence or two saying the state and the transition earns more than the code.

Guess the outputA wrong guess is fine

tail is kept with lower_bound. After 3 1 4 1 5, what is in tail?

1#include <iostream>2#include <vector>3#include <algorithm>4using namespace std;5 6int main() {7    vector<int> a = {3, 1, 4, 1, 5};8    vector<int> tail;9    for (int x : a) {10        auto it = lower_bound(tail.begin(), tail.end(), x);11        if (it == tail.end()) tail.push_back(x);12        else *it = x;13    }14    for (int x : tail)15        cout << x << " ";16    cout << "\n";17    return 0;18}

Summary

Take-away

Three patterns of algorithm design

  • Recognise it: list all → backtracking; each step provably best → greedy; repeating subproblems → DP; independent → divide and conquer
  • Two strings: dp[i][j] for first i and first j; equal looks up-left, unequal above and left
  • One sequence: dp[i] ending at a[i], the answer is max_element; O(n log n) with lower_bound
  • An unordered_map memo: find to look up, print by key, never by iterating
  • Check the input range first: n ≤ 20 can search, n ≥ 10⁵ needs O(n log n)
1vector<vector<int>> dp(n + 1, vector<int>(m + 1, 0));2for (int i = 1; i <= n; i++)3    for (int j = 1; j <= m; j++)4        dp[i][j] = s[i - 1] == t[j - 1] ? dp[i - 1][j - 1] + 15                                       : max(dp[i - 1][j], dp[i][j - 1]);

Chapter 8 quick check

5 questions: the calls of fast power, counting combinations by backtracking, a greedy counterexample, paths through a grid, and a knapsack with its loop the wrong way round. Work out what each prints, then pick.

Guess the outputA wrong guess is fine

How many times is power called for power(1, 100)?

1#include <iostream>2using namespace std;3 4int calls = 0;5 6long long power(long long x, int n) {7    calls++;8    if (n == 0) return 1;9    long long h = power(x, n / 2);10    h = h * h;11    if (n % 2 == 1) h = h * x;12    return h;13}14 15int main() {16    power(1, 100);17    cout << calls << "\n";18    return 0;19}
Guess the outputA wrong guess is fine

Choosing 3 of 1 to 5 (always choosing forwards), how many does the backtracking count?

1#include <iostream>2#include <vector>3using namespace std;4 5int n = 5, k = 3, ways = 0;6vector<int> path;7 8void dfs(int start) {9    if ((int)path.size() == k) {10        ways++;11        return;12    }13    for (int i = start; i <= n; i++) {14        path.push_back(i);15        dfs(i + 1);16        path.pop_back();17    }18}19 20int main() {21    dfs(1);22    cout << ways << "\n";23    return 0;24}
Guess the outputA wrong guess is fine

Coins 10, 7 and 1: how many coins does greedy use to make 14?

1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6    vector<int> coins = {10, 7, 1};7    int amount = 14, count = 0;8    for (int c : coins)9        while (amount >= c) {10            amount -= c;11            count++;12        }13    cout << count << "\n";14    return 0;15}
Guess the outputA wrong guess is fine

On a grid of 3 rows and 4 columns, going from the top-left to the bottom-right, only right or down, how many paths are there?

1#include <iostream>2#include <vector>3using namespace std;4 5int main() {6    vector<vector<int>> dp(3, vector<int>(4));7    for (int i = 0; i < 3; i++)8        for (int j = 0; j < 4; j++)9            if (i == 0 || j == 0) dp[i][j] = 1;10            else dp[i][j] = dp[i - 1][j] + dp[i][j - 1];11    cout << dp[2][3] << "\n";12    return 0;13}
Guess the outputA wrong guess is fine

This was meant to be a 0-1 knapsack (capacity 7, one of each item), but the inner loop runs forwards. What does it print?

1#include <iostream>2#include <vector>3#include <algorithm>4using namespace std;5 6int main() {7    vector<int> w = {2, 3};8    vector<int> v = {3, 5};9    vector<int> dp(8, 0);10    for (int i = 0; i < 2; i++)11        for (int j = w[i]; j <= 7; j++)12            dp[j] = max(dp[j], dp[j - w[i]] + v[i]);13    cout << dp[7] << "\n";14    return 0;15}
Finished this lesson?Mark it. Progress is saved in this browser, and you can undo it.