Hard 3: dynamic programming and backtracking

The DP problems here need two indices or an interval, and the backtracking ones need pruning to finish. For each, write the subproblem definition as a comment before any code; if you cannot state it in one sentence, you are not ready to type.

Longest palindromic subsequence

Write lps(text) that returns the length of the longest subsequence of text (characters in order, not necessarily adjacent) that is a palindrome.

lps("bbbab")  ->  4     (bbbb)
lps("cbbd")   ->  2
lps("")       ->  0

A table over substrings text[i..j]: equal ends add 2 to the inside, otherwise take the better of dropping one end. Fill by increasing length. Equivalent to the longest common subsequence of the text with its reverse.

def lps(text):
    ...

Pattern matching with . and *

Write matches(text, pattern) that returns whether the whole of text matches pattern, where . matches any single character and * means "zero or more of the preceding element". Patterns are valid: * never comes first.

matches("aa", "a")     ->  False
matches("aa", "a*")    ->  True
matches("ab", ".*")    ->  True
matches("aab", "c*a*b")  ->  True
matches("mississippi", "mis*is*p*.")  ->  False

A two-index DP: ok[i][j] means text[i:] matches pattern[j:]. The * case branches into "skip the pair" or "consume one character and stay".

def matches(text, pattern):
    ...

Burst balloons

nums lists the numbers on a row of balloons. Bursting balloon i earns left * nums[i] * right coins, where left and right are the nearest unburst neighbours (treat the edges as 1), and then the row closes up. Write max_coins(nums) that returns the most coins you can earn by bursting all of them.

max_coins([3, 1, 5, 8])  ->  167
max_coins([1, 5])        ->  10
max_coins([])            ->  0

Think about the last balloon burst in a range: its neighbours are the range's fixed borders. Interval DP over (left border, right border) with padding 1s at both ends.

def max_coins(nums):
    ...

Best profit with k trades

prices lists a stock's price each day. You may complete at most k buy-then-sell transactions, never holding more than one share. Write max_profit(prices, k) that returns the largest total profit.

max_profit([2, 4, 1], 2)        ->  2
max_profit([3, 2, 6, 5, 0, 3], 2)  ->  7     (buy 2 sell 6, buy 0 sell 3)
max_profit([7, 6, 4, 3, 1], 1)  ->  0

State per transaction number: the best balance while holding and while not holding. Update both for each day, from higher transaction counts down so a day is not used twice.

def max_profit(prices, k):
    ...

Split into k equal groups

Write can_partition(nums, k) that returns whether the positive whole numbers can be divided into k non-empty groups with equal sums.

can_partition([4, 3, 2, 3, 5, 2, 1], 4)  ->  True     (5), (1,4), (2,3), (2,3)
can_partition([1, 2, 3, 4], 3)           ->  False

Backtracking with k buckets: place each number (largest first) into a bucket that still has room, undo on failure. Skip buckets with the same current total as one already tried.

def can_partition(nums, k):
    ...

Solve a Sudoku

grid is a list of nine strings of nine characters, digits 1-9 or . for empty, with exactly one solution. Write solve(grid) that returns the solved grid in the same format.

solve(["53..7....", "6..195...", ".98....6.", "8...6...3", "4..8.3..1", "7...2...6", ".6....28.", "...419..5", "....8..79"])
    ->  ["534678912", "672195348", "198342567", "859761423", "426853791", "713924856", "961537284", "287419635", "345286179"]

Backtracking cell by cell: for an empty cell, try each digit not already in its row, column or 3x3 box; recurse; undo. Keep three lists of sets so the legality check is constant time.

def solve(grid):
    ...

Every way to split into words

Write all_breaks(text, words) that returns every way to split text into a sequence of words from words (reusable), each as a space-separated sentence. Order of the output does not matter.

all_breaks("catsanddog", ["cat", "cats", "and", "sand", "dog"])  ->  ["cats and dog", "cat sand dog"]
all_breaks("pineapplepenapple", ["apple", "pen", "applepen", "pine", "pineapple"])
    ->  ["pine apple pen apple", "pineapple pen apple", "pine applepen apple"]
all_breaks("catsandog", ["cats", "dog", "sand", "and", "cat"])  ->  []

Backtracking over prefixes, with memoisation of "all sentences for the suffix starting at i" so that shared suffixes are not re-explored.

def all_breaks(text, words):
    ...

Is the string an interleaving?

Write is_interleaving(a, b, c) that returns whether c can be formed by merging a and b while keeping the characters of each in their original order.

is_interleaving("aabcc", "dbbca", "aadbbcbcac")  ->  True
is_interleaving("aabcc", "dbbca", "aadbbbaccc")  ->  False
is_interleaving("", "", "")                      ->  True

A table ok[i][j]: can the first i of a and first j of b make the first i + j of c? A cell is true if the previous character of c came from a or from b.

def is_interleaving(a, b, c):
    ...

Most profitable non-overlapping jobs

jobs is a list of (start, end, profit). Two jobs may both be taken if one ends no later than the other starts. Write max_profit(jobs) that returns the largest total profit from a set of compatible jobs.

max_profit([(1, 3, 50), (2, 4, 10), (3, 5, 40), (3, 6, 70)])  ->  120     (1-3 and 3-6)
max_profit([(1, 2, 5)])  ->  5

Sort by end. best[i] is the best profit using the first i jobs; for job i, either skip it or take it plus best of the last job ending at or before its start, found with bisect.

def max_profit(jobs):
    ...

Longest increasing path in a grid

grid is a list of lists of whole numbers. Write longest_path(grid) that returns the number of cells in the longest path that moves up, down, left or right and strictly increases at every step.

longest_path([[9, 9, 4], [6, 6, 8], [2, 1, 1]])  ->  4     (1, 2, 6, 9)
longest_path([[3, 4, 5], [3, 2, 6], [2, 2, 1]])  ->  4
longest_path([[1]])                              ->  1

Depth-first search from each cell with memoisation of "longest path starting here". No visited set is needed: strictly increasing means no cycles.

def longest_path(grid):
    ...

How many search trees?

Write count_trees(n) that returns how many structurally different binary search trees hold the values 1 to n.

count_trees(1)  ->  1
count_trees(3)  ->  5
count_trees(0)  ->  1

Pick the root: i as root leaves i - 1 values on the left and n - i on the right, and the two sides are independent. Sum over roots. These are the Catalan numbers.

def count_trees(n):
    ...

That is the last page. If you solved these without hints, you are ready for any interview that tests algorithms; the rest is practice under time.