Skip to lesson

Practice: backtracking

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

You have seen subsets, permutations, combinations, grids, N-Queens, and Sudoku. Now we will solve four more top interview problems—Generate Parentheses, Phone Keypad Combinations, Palindrome Partitioning, and Partition to K Equal Sum Subsets—and see how every single one is just a different plug-in of Choices, Constraints, and Goal inside the same five-line template.

Generate valid parentheses and phone letter combinations

Problem 1 — Generate Parentheses: Given n pairs of parentheses (1 <= n <= 8), generate all combinations of well-formed (balanced) parentheses. For n = 3, the output is ["((()))", "(()())", "(())()", "()(())", "()()()"].

Example 1 · Generate Valid Parentheses (open < n and close < open)

GenerateParentheses.javaJava
import java.util.ArrayList;import java.util.List;
public class GenerateParentheses {    public static List<String> generateParenthesis(int n) {        List<String> results = new ArrayList<>();        backtrack(n, 0, 0, new StringBuilder(), results);        return results;    }
    private static void backtrack(int n, int open, int close,                                  StringBuilder current, List<String> results) {        if (current.length() == 2 * n) {            results.add(current.toString());            return;        }        if (open < n) {            current.append('(');            backtrack(n, open + 1, close, current, results);            current.deleteCharAt(current.length() - 1);        }        if (close < open) {            current.append(')');            backtrack(n, open, close + 1, current, results);            current.deleteCharAt(current.length() - 1);        }    }
    public static void main(String[] args) {        System.out.println("n = 2: " + generateParenthesis(2));        System.out.println("n = 3: " + generateParenthesis(3));    }}
Output
n = 2: [(()), ()()]
n = 3: [((())), (()()), (())(), ()(()), ()()()]

What this code does

  • Because we only append '(' when open < n and only append ')' when close < open, the search never visits an unbalanced prefix like ")(" or "())".
  • The number of valid n-pair strings is the n-th Catalan number Cₙ = 1/(n + 1)C(2n, n) (1, 2, 5, 14, 42...).

Example 2 · Letter Combinations of a Phone Number & Palindrome Partitioning

PhoneAndPalindrome.javaJava
import java.util.ArrayList;import java.util.List;
public class PhoneAndPalindrome {    private static final String[] KEYPAD = {        "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"    };
    public static List<String> letterCombinations(String digits) {        List<String> results = new ArrayList<>();        if (digits == null || digits.isEmpty()) return results;        phoneBacktrack(digits, 0, new StringBuilder(), results);        return results;    }
    private static void phoneBacktrack(String digits, int idx, StringBuilder path, List<String> res) {        if (idx == digits.length()) {            res.add(path.toString());            return;        }        String letters = KEYPAD[digits.charAt(idx) - '0'];        for (int i = 0; i < letters.length(); i++) {            path.append(letters.charAt(i));            phoneBacktrack(digits, idx + 1, path, res);            path.deleteCharAt(path.length() - 1);        }    }
    public static List<List<String>> partitionPalindromes(String s) {        List<List<String>> results = new ArrayList<>();        palBacktrack(s, 0, new ArrayList<>(), results);        return results;    }
    private static void palBacktrack(String s, int start, List<String> current, List<List<String>> res) {        if (start == s.length()) {            res.add(new ArrayList<>(current));            return;        }        for (int end = start; end < s.length(); end++) {            if (isPalindrome(s, start, end)) {                current.add(s.substring(start, end + 1));                palBacktrack(s, end + 1, current, res);                current.remove(current.size() - 1);            }        }    }
    private static boolean isPalindrome(String s, int l, int r) {        while (l < r) {            if (s.charAt(l++) != s.charAt(r--)) return false;        }        return true;    }
    public static void main(String[] args) {        System.out.println("Phone '23': " + letterCombinations("23"));        System.out.println("Partitions of 'aab': " + partitionPalindromes("aab"));        System.out.println("Partitions of 'racecar': " + partitionPalindromes("racecar"));    }}
Output
Phone '23': [ad, ae, af, bd, be, bf, cd, ce, cf]
Partitions of 'aab': [[a, a, b], [aa, b]]
Partitions of 'racecar': [[r, a, c, e, c, a, r], [r, a, cec, a, r], [r, aceca, r], [racecar]]

What this code does

  • In phoneBacktrack, level idx chooses one character from KEYPAD[digits.charAt(idx) - '0'] and advances to idx + 1.
  • In palBacktrack, level start chooses the end index end of the next palindrome piece s[start .. end] and recurses on the remaining suffix starting at end + 1.

Instead of generating all 2²ⁿ strings of '(' and ')' and checking balance at the end, track two counts—open (how many '(' used so far) and close (how many ')' used so far)—and prune invalid prefixes immediately:

  • Goal: path.length() == 2 * n → record path.toString().
  • Choice 1 ('('): Legal whenever open < n.
  • Choice 2 (')'): Legal whenever close < open (you can only close a bracket that is currently open!). Problem 2 — Letter Combinations of a Phone Number: Given a string digits containing '2'–'9' ("23"), return all letter strings that the number could represent on a telephone keypad (2: "abc", 3: "def", ..., 7: "pqrs", 8: "tuv", 9: "wxyz"). At index idx of digits, look up the keypad letters for digits.charAt(idx), loop over each letter ch, append ch, recurse on idx + 1, and deleteCharAt.
Remember the empty-input edge case on Phone Keypad: when digits.isEmpty(), return an empty list [] (not [""]).

Palindrome partitioning

Problem 3 — Palindrome Partitioning: Given a string s (1 <= s.length() <= 16), partition s such that every substring of the partition is a palindrome, and return all possible palindrome partitionings. For s = "aab", the output is [["a", "a", "b"], ["aa", "b"]].

Think of partitioning s from index start as choosing where the first cut ends! At index start, any index end from start to s.length() - 1 defines a candidate prefix piece s[start .. end]:

  1. Goal: When start == s.length(), the entire string has been cut into palindromes—add new ArrayList<>(current) to results and return.
  2. Loop over cut positions: For int end = start; end < s.length(); end++, check the constraint isPalindrome(s, start, end) with two pointers.
  3. Prune non-palindromes: If s[start .. end] is not a palindrome, continue—do not recurse on the suffix end + 1!
  4. Choose, explore, un-choose: Add s.substring(start, end + 1) to current, call backtrack(s, end + 1, current, results), and remove the last string from current.

Partition to K equal sum subsets and reusing one template

Problem 4 — Partition to K Equal Sum Subsets.

Example 3 · Partition to K Equal Sum Subsets with Fail-First & Symmetry Pruning

PartitionKSubsetsDemo.javaJava
import java.util.Arrays;
public class PartitionKSubsetsDemo {    public static boolean canPartitionKSubsets(int[] nums, int k) {        int sum = 0;        for (int x : nums) sum += x;        if (sum % k != 0) return false;        int target = sum / k;
        Arrays.sort(nums);        int n = nums.length;        if (nums[n - 1] > target) return false;
        int[] buckets = new int[k];        return backtrack(nums, n - 1, buckets, target);    }
    private static boolean backtrack(int[] nums, int idx, int[] buckets, int target) {        if (idx < 0) {            return true; // Every element has been placed into a valid bucket!        }        int val = nums[idx];        for (int b = 0; b < buckets.length; b++) {            if (buckets[b] + val <= target) {                buckets[b] += val; // 1. Choose bucket b                if (backtrack(nums, idx - 1, buckets, target)) {                    return true;   // 2. Explore                }                buckets[b] -= val; // 3. Un-choose            }            // Symmetry pruning: if bucket b is empty and placing val here failed,            // every subsequent empty bucket b+1..k-1 will fail identically!            if (buckets[b] == 0) {                break;            }        }        return false;    }
    public static void main(String[] args) {        int[] a = {4, 3, 2, 3, 5, 2, 1};        System.out.println("[4,3,2,3,5,2,1], k=4 -> " + canPartitionKSubsets(a, 4));
        int[] b = {1, 2, 3, 4};        System.out.println("[1,2,3,4], k=3 -> " + canPartitionKSubsets(b, 3));
        int[] c = {2, 2, 2, 2, 3, 4, 5};        System.out.println("[2,2,2,2,3,4,5], k=4 -> " + canPartitionKSubsets(c, 4));    }}
Output
[4,3,2,3,5,2,1], k=4 -> true
[1,2,3,4], k=3 -> false
[2,2,2,2,3,4,5], k=4 -> false

What this code does

  • Sorting nums and recursing from n - 1 down to 0 places the largest numbers (5, 4, 3...) first, immediately exposing impossible bucket sums.
  • The line if (buckets[b] == 0) break; eliminates the k! permutation symmetry among empty buckets, turning a O(kⁿ) worst-case search into a sub-millisecond check for n ≤ 16.

Given an integer array nums (1 <= k <= nums.length <= 16, 1 <= nums[i] <= 10_000) and an integer k, return true if nums can be partitioned into k non-empty subsets whose sums are all equal (target = totalSum / k). Notice how all four pruning rules from the previous lesson combine here! First, if totalSum % k != 0, return false. Otherwise sort nums and place elements from largest to smallest (idx = n - 1 down to 0) into int[] buckets = new int[k]. At element nums[idx], try each bucket b where buckets[b] + nums[idx] <= target. And if buckets[b] == 0 after a failed recursive call, break immediately—all remaining empty buckets are symmetric! Look across all eight lessons of this module—every problem is the same template with three blanks filled in:

  • Subsets / Combinations: start index, choices i = start .. n - 1, recurse with i + 1 (or i for reuse).
  • Permutations: boolean[] used, choices i = 0 .. n - 1 where !used[i].
  • String / Sequence building (Parentheses, Phone Keypad, Palindrome Partitioning): index idx or counts (open, close), append piece, recurse, undo.
  • Bucket / Grid constraint satisfaction (Word Search, N-Queens, Sudoku, K-Subsets): step idx/r/pos, check capacity or board safety, assign state, recurse, restore state.

Finish up

Mark complete & continue

Next: Binary numbers