cswork / templatesOpen the Line 500 list

STOP 20 · BACKTRACKING

String Partitioning and Construction

Backtrack over cut points with a palindrome table O(n · 2^n)

Contest ratings Rating 1740–Rating 1740· median Rating 1740(1 of 10 problems rated by zerotrac)

Open the Line 500 list · stop 20 · 10 problems
Learn first
Leads to
No later stop builds on it.
How often asked
asked by 1 company · in 1 reportSalesforce 1

Warm up with this one

LC 22Generate ParenthesesMedium
Stuck? Peek at the approach

Track opening and closing counts and prune invalid prefixes during construction.

Key points

  1. Each level decides where the next piece ends; when start reaches n you have one complete split.
  2. Precompute an O(n²) table of which substrings are palindromes so each check inside the search is O(1).
  3. Restoring IP addresses and word break use the same frame; only the "is this piece valid" test changes.

Common pitfalls

  • Re-checking palindromes with two pointers inside the search repeats work and inflates the constant.
  • If you only need the number of ways or the fewest cuts, don't enumerate; use DP.
  • Keep one convention for substring bounds; s[start:end+1] and substring(start, end+1) are easy to get off by one.

Watch it run

Step through the pattern on a small example. Pause, step forwards or back, or drag the slider to any step.

Interactive demo · step by step

Backtracking · the subset decision tree

List every subset of [1, 2, 3]

Try your own input
{}
CurrentDiscovered / computedAnswer
Subsets collected
Empty
Depth
0
Path
{}
Results
0

Start from the empty set; first decide whether to take 1.

InvariantEach level decides one number, take or skip; returning undoes that choice so the path is restored before the other branch.

Template

Open one language. All four implement the same template, and each one is compiled, run and checked against test data. Then rewrite the warm-up, LC 22, with it.

Python
def partition(s: str) -> list[list[str]]:
    """Every way to cut s into palindromes."""
    n = len(s)
    pal = [[False] * n for _ in range(n)]  # pal[i][j]: s[i..j] is a palindrome
    for i in range(n - 1, -1, -1):
        for j in range(i, n):
            pal[i][j] = s[i] == s[j] and (j - i < 2 or pal[i + 1][j - 1])
    res, path = [], []

    def dfs(start: int) -> None:
        if start == n:
            res.append(path[:])
            return
        for end in range(start, n):  # the next piece is s[start..end]
            if pal[start][end]:
                path.append(s[start : end + 1])
                dfs(end + 1)
                path.pop()

    dfs(0)
    return res
C++
// Every way to cut s into palindromes.
vector<vector<string>> partition(const string& s) {
    int n = s.size();
    vector<vector<bool>> pal(n, vector<bool>(n, false));  // pal[i][j]: s[i..j] is a palindrome
    for (int i = n - 1; i >= 0; i--)
        for (int j = i; j < n; j++) pal[i][j] = s[i] == s[j] && (j - i < 2 || pal[i + 1][j - 1]);
    vector<vector<string>> res;
    vector<string> path;
    function<void(int)> dfs = [&](int start) {
        if (start == n) {
            res.push_back(path);
            return;
        }
        for (int end = start; end < n; end++)  // the next piece is s[start..end]
            if (pal[start][end]) {
                path.push_back(s.substr(start, end - start + 1));
                dfs(end + 1);
                path.pop_back();
            }
    };
    dfs(0);
    return res;
}
Java
class Solution {
    private final List<List<String>> res = new ArrayList<>();
    private final List<String> path = new ArrayList<>();
    private boolean[][] pal; // pal[i][j]: s[i..j] is a palindrome
    private String s;

    // Every way to cut s into palindromes.
    List<List<String>> partition(String s) {
        int n = s.length();
        this.s = s;
        pal = new boolean[n][n];
        for (int i = n - 1; i >= 0; i--)
            for (int j = i; j < n; j++)
                pal[i][j] = s.charAt(i) == s.charAt(j) && (j - i < 2 || pal[i + 1][j - 1]);
        res.clear();
        dfs(0);
        return res;
    }

    private void dfs(int start) {
        if (start == s.length()) {
            res.add(new ArrayList<>(path));
            return;
        }
        for (int end = start; end < s.length(); end++) // the next piece is s[start..end]
            if (pal[start][end]) {
                path.add(s.substring(start, end + 1));
                dfs(end + 1);
                path.remove(path.size() - 1);
            }
    }
}
Go
// partition returns every way to cut s into palindromes.
func partition(s string) [][]string {
	n := len(s)
	pal := make([][]bool, n) // pal[i][j]: s[i..j] is a palindrome
	for i := range pal {
		pal[i] = make([]bool, n)
	}
	for i := n - 1; i >= 0; i-- {
		for j := i; j < n; j++ {
			pal[i][j] = s[i] == s[j] && (j-i < 2 || pal[i+1][j-1])
		}
	}
	var res [][]string
	var path []string
	var dfs func(start int)
	dfs = func(start int) {
		if start == n {
			res = append(res, append([]string(nil), path...))
			return
		}
		for end := start; end < n; end++ { // the next piece is s[start..end]
			if pal[start][end] {
				path = append(path, s[start:end+1])
				dfs(end + 1)
				path = path[:len(path)-1]
			}
		}
	}
	dfs(0)
	return res
}

Common variants

Problems at this stop also need the 2 shapes below. Open one to see when to switch to it; its code is tested in all four languages too.

Generate brackets under count constraintsO(4^n / √n) time (a Catalan number of results) · O(n) recursion depth

When each step picks from a few characters and counts alone can prune (brackets, IP segments, letter case): an opening bracket fits while some are left, a closing one only while fewer have closed than opened, so everything reaching length 2n is valid with no final check. LC 22 (Generate Parentheses); LC 301 (Remove Invalid Parentheses) uses the same counts.

Python
def generate_parentheses(n: int) -> list[str]:
    """Every balanced string of n pairs of parentheses (LC 22)."""
    res, path = [], []

    def dfs(opened: int, closed: int) -> None:
        if len(path) == 2 * n:
            res.append("".join(path))
            return
        if opened < n:  # an opening bracket fits while some are left
            path.append("(")
            dfs(opened + 1, closed)
            path.pop()
        if closed < opened:  # a closing bracket needs an unmatched opening one
            path.append(")")
            dfs(opened, closed + 1)
            path.pop()

    dfs(0, 0)
    return res
C++
// Every balanced string of n pairs of parentheses (LC 22).
vector<string> generateParentheses(int n) {
    vector<string> res;
    string path;
    function<void(int, int)> dfs = [&](int opened, int closed) {
        if ((int)path.size() == 2 * n) {
            res.push_back(path);
            return;
        }
        if (opened < n) {  // an opening bracket fits while some are left
            path.push_back('(');
            dfs(opened + 1, closed);
            path.pop_back();
        }
        if (closed < opened) {  // a closing bracket needs an unmatched opening one
            path.push_back(')');
            dfs(opened, closed + 1);
            path.pop_back();
        }
    };
    dfs(0, 0);
    return res;
}
Java
class Solution {
    private final List<String> res = new ArrayList<>();
    private final StringBuilder path = new StringBuilder();
    private int n;

    // Every balanced string of n pairs of parentheses (LC 22).
    List<String> generateParentheses(int n) {
        this.n = n;
        res.clear();
        dfs(0, 0);
        return new ArrayList<>(res);
    }

    private void dfs(int opened, int closed) {
        if (path.length() == 2 * n) {
            res.add(path.toString());
            return;
        }
        if (opened < n) { // an opening bracket fits while some are left
            path.append('(');
            dfs(opened + 1, closed);
            path.deleteCharAt(path.length() - 1);
        }
        if (closed < opened) { // a closing bracket needs an unmatched opening one
            path.append(')');
            dfs(opened, closed + 1);
            path.deleteCharAt(path.length() - 1);
        }
    }
}
Go
// generateParentheses returns every balanced string of n pairs of parentheses (LC 22).
func generateParentheses(n int) []string {
	var res []string
	path := make([]byte, 0, 2*n)
	var dfs func(opened, closed int)
	dfs = func(opened, closed int) {
		if len(path) == 2*n {
			res = append(res, string(path))
			return
		}
		if opened < n { // an opening bracket fits while some are left
			path = append(path, '(')
			dfs(opened+1, closed)
			path = path[:len(path)-1]
		}
		if closed < opened { // a closing bracket needs an unmatched opening one
			path = append(path, ')')
			dfs(opened, closed+1)
			path = path[:len(path)-1]
		}
	}
	dfs(0, 0)
	return res
}
Cut a digit string and insert operatorsO(n · 4^n) time · O(n) recursion depth

To place + - * between digits and find the expressions that hit a target: each level chooses where the next number ends (no leading zeros) and recurses once per operator. Multiplication binds tighter, so carry the last term: a * subtracts it and adds last × x instead. LC 282 (Expression Add Operators).

Python
def add_operators(num: str, target: int) -> list[str]:
    """Every way to put + - * between the digits of num so it equals target (LC 282)."""
    res = []

    def dfs(i: int, expr: str, value: int, last: int) -> None:
        # value: the expression so far; last: its final term, which a * must take back
        if i == len(num):
            if value == target:
                res.append(expr)
            return
        for j in range(i, len(num)):
            if j > i and num[i] == "0":
                break  # no numbers with a leading zero
            s = num[i : j + 1]
            x = int(s)
            if i == 0:
                dfs(j + 1, s, x, x)
            else:
                dfs(j + 1, expr + "+" + s, value + x, x)
                dfs(j + 1, expr + "-" + s, value - x, -x)
                dfs(j + 1, expr + "*" + s, value - last + last * x, last * x)  # * binds tighter

    dfs(0, "", 0, 0)
    return res
C++
// Every way to put + - * between the digits of num so it equals target (LC 282).
vector<string> addOperators(const string& num, long long target) {
    vector<string> res;
    // value: the expression so far; last: its final term, which a * must take back
    function<void(size_t, const string&, long long, long long)> dfs = [&](size_t i, const string& expr, long long value, long long last) {
        if (i == num.size()) {
            if (value == target) res.push_back(expr);
            return;
        }
        for (size_t j = i; j < num.size(); j++) {
            if (j > i && num[i] == '0') break;  // no numbers with a leading zero
            string s = num.substr(i, j - i + 1);
            long long x = stoll(s);
            if (i == 0) {
                dfs(j + 1, s, x, x);
            } else {
                dfs(j + 1, expr + "+" + s, value + x, x);
                dfs(j + 1, expr + "-" + s, value - x, -x);
                dfs(j + 1, expr + "*" + s, value - last + last * x, last * x);  // * binds tighter
            }
        }
    };
    dfs(0, "", 0, 0);
    return res;
}
Java
class Solution {
    private final List<String> res = new ArrayList<>();
    private String num;
    private long target;

    // Every way to put + - * between the digits of num so it equals target (LC 282).
    List<String> addOperators(String num, long target) {
        this.num = num;
        this.target = target;
        res.clear();
        dfs(0, "", 0, 0);
        return new ArrayList<>(res);
    }

    // value: the expression so far; last: its final term, which a * must take back.
    private void dfs(int i, String expr, long value, long last) {
        if (i == num.length()) {
            if (value == target) res.add(expr);
            return;
        }
        for (int j = i; j < num.length(); j++) {
            if (j > i && num.charAt(i) == '0') break; // no numbers with a leading zero
            String s = num.substring(i, j + 1);
            long x = Long.parseLong(s);
            if (i == 0) {
                dfs(j + 1, s, x, x);
            } else {
                dfs(j + 1, expr + "+" + s, value + x, x);
                dfs(j + 1, expr + "-" + s, value - x, -x);
                dfs(j + 1, expr + "*" + s, value - last + last * x, last * x); // * binds tighter
            }
        }
    }
}
Go
import "strconv"

// addOperators returns every way to put + - * between the digits of num so it equals target (LC 282).
func addOperators(num string, target int) []string {
	res := []string{}
	// value: the expression so far; last: its final term, which a * must take back
	var dfs func(i int, expr string, value, last int)
	dfs = func(i int, expr string, value, last int) {
		if i == len(num) {
			if value == target {
				res = append(res, expr)
			}
			return
		}
		for j := i; j < len(num); j++ {
			if j > i && num[i] == '0' {
				break // no numbers with a leading zero
			}
			s := num[i : j+1]
			x, _ := strconv.Atoi(s)
			if i == 0 {
				dfs(j+1, s, x, x)
			} else {
				dfs(j+1, expr+"+"+s, value+x, x)
				dfs(j+1, expr+"-"+s, value-x, -x)
				dfs(j+1, expr+"*"+s, value-last+last*x, last*x) // * binds tighter
			}
		}
	}
	dfs(0, "", 0, 0)
	return res
}

Why it works

  1. Every way to split corresponds to exactly one increasing sequence of cut points, and each level of the search picks where the next piece ends, so every split is generated exactly once.
  2. The palindrome table isPal[i][j] = (s[i] == s[j]) and isPal[i+1][j−1] depends only on shorter ranges, so filling i from the back guarantees every entry is ready when used.
  3. Pruning cuts only branches whose current piece is invalid; an invalid piece can appear in no valid split, so nothing is lost.

Say it in 30 seconds

When the interviewer asks you to talk it through: the approach, why it is correct, then the cost. One version in each language to read aloud a few times.

中文
字符串切分我用回溯,每一层决定下一段在哪里结束,start 走到末尾就得到一种完整切分;每种切分对应唯一一串切点,所以不重不漏。判断某一段是否回文,我先用 O(n²) 的区间 DP 预处理,搜索里每次检查就是 O(1)。复原 IP、单词拆分也是同一个框架,只是这一段是否合法的判断不同。答案数最坏是指数级,复杂度 O(n · 2^n)。
English
To partition a string I backtrack, and each level chooses where the next piece ends; when start reaches the end I have one complete split, and since each split is a unique sequence of cuts, none repeats or goes missing. I precompute an O(n²) palindrome table so each check inside the search is O(1). Restoring IP addresses and word break use the same frame with a different validity test. The number of answers can be exponential, so the worst case is O(n · 2^n).

Grade yourself

Grade your answer against the one above. Questions you have not mastered come back after 1, 3, 7 and 21 days, listed under My progress → Due for review. Kept on this device; sign in and it moves to your account.

Key points you covered (0 of 3)
How well did you know it?

Quick quiz

3 concept and complexity questions. Answered ones come back for spaced review along with the OA multiple-choice practice. Open the OA multiple-choice practice

3 questions
  1. When backtracking over all valid strings of n parenthesis pairs, when may you append ")"?
  2. How many balanced strings can 3 pairs of parentheses form?
  3. When backtracking over every palindrome partition of s (length n), what does precomputing a table pal[i][j] (is s[i..j] a palindrome) change?

Your answers stay in this browser on this device; open OA multiple-choice practice signed in to keep them in your account.

Template drills

Drills cut from the templates above: put shuffled lines back in order, fill the blanked boundary conditions back in, or write a whole template from memory in an empty editor, run against this stop's tests and compared line by line. Another one gives a new drill.

These lines are shuffled. Tap a line to pick it, then tap another to swap them, until they read as the template does; the indentation is a hint.

def partition(s: str) -> list[list[str]]:
    """Every way to cut s into palindromes."""
    n = len(s)
    pal = [[False] * n for _ in range(n)]
    for i in range(n - 1, -1, -1):

    dfs(0)
    return res

Practice by stage

This stop's 10 Line 500 problems in three stages: Foundation, Core and Advanced. Each has a one-line approach; try it yourself before reading it.

Core 5

#ProblemApproachRating
22Generate ParenthesesTrack opening and closing counts and prune invalid prefixes during construction.
131Palindrome PartitioningEnumerate cut positions and verify palindromes to construct every valid partition.
93Restore IP AddressesSplit an IP address into segments, handling leading zeros, segment length, and numeric bounds.
320Generalized Abbreviation 🔒Track the length of a consecutive abbreviation and emit its count when retaining a character.
254Factor Combinations 🔒Enumerate factorizations with nondecreasing factors to avoid duplicate answers from factor permutations.

Advanced 5

#ProblemApproachRating
267Palindrome Permutation II 🔒Check frequency parity first, then permute half the characters to generate unique palindromes.
291Word Pattern II 🔒Build a bijection between pattern characters and substrings through backtracking and reverse mappings.
1593Split a String Into the Max Number of Unique SubstringsEnumerate string partitions while tracking used substrings, pruning with the remaining length.Rating 1740
301Remove Invalid ParenthesesGenerate valid parenthesis strings with the minimum number of deletions and remove duplicate answers.
282Expression Add OperatorsTrack the accumulated value and previous term when inserting operators, preserving multiplication precedence and rejecting leading zeros.

OA questions on this topic 1

All 1