Backtracking
All of these follow the template: choose, recurse, undo. The difference between them is the pruning rule and how duplicates are avoided.
The lesson is Backtracking.
Subsets with repeated values
Write unique_subsets(items) that returns every distinct subset of a list that may
contain repeated values, as a list of lists. Two subsets are the same if they contain the
same values the same number of times. Order of the output does not matter; each subset
should be in non-decreasing order.
unique_subsets([1, 2, 2]) -> [[], [1], [1, 2], [1, 2, 2], [2], [2, 2]]
unique_subsets([]) -> [[]]
The point is to practise skipping duplicate choices at the same level after sorting.
def unique_subsets(items):
...
Choose k from n
Write combinations(n, k) that returns every way to choose k distinct numbers from
1 to n, each as an increasing list. Order of the output does not matter.
combinations(4, 2) -> [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]
combinations(3, 3) -> [[1, 2, 3]]
combinations(3, 0) -> [[]]
The point is to practise the start index pattern with a size limit, and pruning when
too few numbers remain.
def combinations(n, k):
...
Distinct orderings with repeats
Write unique_permutations(items) that returns every distinct ordering of a list that
may contain repeated values. Order of the output does not matter.
unique_permutations([1, 1, 2]) -> [[1, 1, 2], [1, 2, 1], [2, 1, 1]]
unique_permutations([]) -> [[]]
The point is to practise the duplicate-skip rule in the permutation template: at each slot, do not place a value equal to one you already tried in that slot.
def unique_permutations(items):
...
Every mix of upper and lower case
Write case_variants(text) that returns every string obtainable by changing the case of
any letters in text; digits stay as they are. Order of the output does not matter.
case_variants("a1b") -> ["a1b", "a1B", "A1b", "A1B"]
case_variants("12") -> ["12"]
The point is to practise a two-way branch per position, with a position that offers only one choice.
def case_variants(text):
...
All balanced bracket strings
Write balanced(n) that returns every string made of n ( and n ) that is
correctly balanced. Order of the output does not matter.
balanced(1) -> ["()"]
balanced(2) -> ["(())", "()()"]
balanced(3) -> ["((()))", "(()())", "(())()", "()(())", "()()()"]
The point is to practise pruning with two counters: add ( while some remain, add )
only while there are more ( than ) so far.
def balanced(n):
...
Letters a phone number could spell
On an old phone keypad 2 is abc, 3 is def, 4 is ghi, 5 is jkl, 6 is mno,
7 is pqrs, 8 is tuv, 9 is wxyz. Write spellings(digits) that returns every
string the digits (all between 2 and 9) could spell. Order of the output does not matter.
spellings("23") -> ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]
spellings("") -> []
The point is to practise a backtracking loop whose choices come from a lookup table.
def spellings(digits):
...
Find a word in a letter grid
grid is a list of strings of letters. Write exists(grid, word) that returns whether
word can be traced through adjacent cells (up, down, left, right), using each cell at
most once.
grid = ["ABCE", "SFCS", "ADEE"]
exists(grid, "ABCCED") -> True
exists(grid, "SEE") -> True
exists(grid, "ABCB") -> False
The point is to practise backtracking on a grid with a visited set that is undone.
def exists(grid, word):
...
Cut into palindromes
Write palindrome_cuts(text) that returns every way to cut text into pieces that are
each a palindrome, as a list of lists of strings. Order of the output does not matter.
palindrome_cuts("aab") -> [["a", "a", "b"], ["aa", "b"]]
palindrome_cuts("a") -> [["a"]]
The point is to practise backtracking over cut positions, pruning any prefix that is not a palindrome.
def palindrome_cuts(text):
...
Combination sum, each number once
Write combos_once(candidates, target) that returns every distinct combination of numbers
from candidates (which may contain repeats) that sums to target, using each position
at most once. Each combination is in non-decreasing order and no combination appears twice.
Order of the output does not matter.
combos_once([10, 1, 2, 7, 6, 1, 5], 8) -> [[1, 1, 6], [1, 2, 5], [1, 7], [2, 6]]
combos_once([2, 5, 2, 1, 2], 5) -> [[1, 2, 2], [5]]
The point is to practise combining the start + 1 rule (no reuse) with the duplicate
skip at the same level.
def combos_once(candidates, target):
...
k distinct digits with a given sum
Write digit_combos(k, n) that returns every combination of k distinct digits from 1 to
9 whose sum is n, each as an increasing list. Order of the output does not matter.
digit_combos(3, 7) -> [[1, 2, 4]]
digit_combos(3, 9) -> [[1, 2, 6], [1, 3, 5], [2, 3, 4]]
digit_combos(4, 1) -> []
The point is to practise two constraints at once, size and sum, each of which can prune.
def digit_combos(k, n):
...