This site uses one functional cookie to keep feature rollouts consistent for you. Nothing is set until you choose. See the privacy notice.
Phase 3: Search and graphs
Choose, explore, un-choose. Prune anything that can't work.
Builds on Tree DFS.
The question to ask
Am I asked to list every valid arrangement, and can I build one choice at a time and undo it?
When a question asks for all combinations, permutations, subsets or arrangements, there's no shortcut around generating them, so the job is to generate them without waste. Build a candidate one choice at a time, recurse, then undo the choice and try the next. The recursion tree is the search space; pruning cuts off branches that can no longer lead to an answer. Tiny constraints (n ≤ 15 or so) are the giveaway that exponential time is expected.
Want to watch it run first? Step through the interactive walkthrough.
Time O(branches^depth), e.g. O(n · 2^n) for subsets, O(n · n!) for permutations · Space O(depth) plus the output
Write it from memory first, in an editor or on paper, then check. Recalling it is what makes it stick; reading it again mostly doesn't.
Order matters, so every unused element is a choice at every level. A boolean array marks what's on the path.
function permute(nums: number[]): number[][] {
const result: number[][] = [];
const path: number[] = [];
const used = new Array<boolean>(nums.length).fill(false);
function build(): void {
if (path.length === nums.length) {
result.push([...path]);
return;
}
for (let i = 0; i < nums.length; i++) {
if (used[i]) continue;
used[i] = true;
path.push(nums[i]);
build();
path.pop();
used[i] = false;
}
}
build();
return result;
}Candidates can be reused, so recurse with i, not i + 1. Sorting first means once a candidate is too big, every later one is too, so break instead of continue.
function combinationSum(candidates: number[], target: number): number[][] {
const sorted = [...candidates].sort((a, b) => a - b);
const result: number[][] = [];
const path: number[] = [];
function build(start: number, remaining: number): void {
if (remaining === 0) {
result.push([...path]);
return;
}
for (let i = start; i < sorted.length; i++) {
if (sorted[i] > remaining) break;
path.push(sorted[i]);
build(i, remaining - sorted[i]);
path.pop();
}
}
build(0, target);
return result;
}Easy to hard. Read the prompt and name the signal before opening the tell. After each attempt, rate it: Again brings it back tomorrow, Hard holds the interval, Good and Easy push it further out.
Return all root-to-leaf paths of a binary tree as strings like '1->2->5'.
"All" paths: push the node onto the path, recurse into children, pop on the way back. The gentlest backtracking there is.
Not attempted yet
Given distinct integers, return all possible subsets (the power set), without duplicate subsets.
"All possible" "subsets": the template. Record every node of the recursion tree.
Not attempted yet
The array may contain duplicates. Return all possible subsets without duplicate subsets.
Subsets with duplicates: sort, and skip an element equal to its previous sibling at the same level.
Not attempted yet
Given an array of distinct integers, return all possible permutations.
"All possible permutations": every unused element at every level, tracked with a used array.
Not attempted yet
Return all unique combinations of candidates that sum to target. The same number may be chosen unlimited times.
"Unique combinations" with reuse: recurse from i rather than i + 1, and stop once a candidate exceeds what's left.
Not attempted yet
Each candidate may be used once and the candidates contain duplicates. Return all unique combinations summing to target.
Once each plus duplicates: sort, recurse from i + 1, skip equal siblings.
Not attempted yet
Return all possible combinations of k numbers chosen from 1 to n.
"All possible combinations" of size k: record when the path reaches k; prune when too few numbers remain.
Not attempted yet
Given a string of digits 2 to 9, return all possible letter combinations the number could represent on a phone keypad.
"Letter combinations": one recursion level per digit, one branch per letter on that key.
Not attempted yet
Given n pairs, generate all combinations of well-formed parentheses.
"Generate all" "well-formed": add ( while opens remain, add ) only while closes are fewer than opens. That pruning keeps every path valid.
Not attempted yet
Return true if the word can be traced through sequentially adjacent cells of a letter grid, using each cell at most once.
"Adjacent cells", each used once: DFS, mark the cell visited, recurse to four neighbours, unmark on the way back.
Not attempted yet
Partition a string so every substring of the partition is a palindrome. Return all possible palindrome partitionings.
"Partition" and "all possible": choose the next cut where the prefix is a palindrome, recurse on the rest.
Not attempted yet
Place n queens on an n by n chessboard so that no two attack each other. Return all distinct solutions.
"N-queens": one queen per row; Sets of used columns and both diagonals (r - c and r + c) prune in O(1).
Not attempted yet
Fill the empty cells of a sudoku board so every row, column and 3 by 3 box contains the digits 1 to 9 exactly once.
"Sudoku": find an empty cell, try each digit allowed by its row, column and box, recurse, undo on failure.
Not attempted yet