cswork / templatesOpen the Line 500 list

STOP 19 · BACKTRACKING

Backtracking Enumeration and Deduplication

Choose, recurse, undo; skip duplicates on the same level O(n · 2^n)

Contest ratings Rating 1342–Rating 1741· median Rating 1542(2 of 12 problems rated by zerotrac)

Open the Line 500 list · stop 19 · 12 problems
Learn first
Leads to
How often asked
asked by 2 companies · in 2 reportsLinkedIn 1, Meta 1

Warm up with this one

LC 78SubsetsMedium
Stuck? Peek at the approach

Enumerate subsets by choosing or skipping each element, making exactly one decision per position.

Key points

  1. The template is three moves: choose, recurse, undo. path is a single buffer shared by the whole search.
  2. Sort first, then skip with i > start && nums[i] == nums[i-1]: a value is not reused on the same level, but deeper levels may use it.
  3. Combinations pick from start onward so {1,2} and {2,1} don't both appear; permutations scan from the beginning with a used array.

Common pitfalls

  • Storing a reference to path leaves every result as the same empty list once the search finishes.
  • Writing i > 0 instead of i > start also skips legitimate repeats on deeper levels.
  • Forgetting to sort leaves equal values apart, and the duplicate check does nothing.

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 78, with it.

Python
def subsets_with_dup(nums: list[int]) -> list[list[int]]:
    nums = sorted(nums)  # equal values become neighbours
    res, path = [], []

    def dfs(start: int) -> None:
        res.append(path[:])  # copy: path keeps changing
        for i in range(start, len(nums)):
            if i > start and nums[i] == nums[i - 1]:
                continue  # this value was already tried at this level
            path.append(nums[i])
            dfs(i + 1)
            path.pop()  # undo the choice

    dfs(0)
    return res
C++
vector<vector<int>> subsetsWithDup(vector<int> nums) {
    sort(nums.begin(), nums.end());  // equal values become neighbours
    vector<vector<int>> res;
    vector<int> path;
    function<void(int)> dfs = [&](int start) {
        res.push_back(path);  // copies path
        for (int i = start; i < (int)nums.size(); i++) {
            if (i > start && nums[i] == nums[i - 1]) continue;  // already tried at this level
            path.push_back(nums[i]);
            dfs(i + 1);
            path.pop_back();  // undo the choice
        }
    };
    dfs(0);
    return res;
}
Java
class Solution {
    private final List<List<Integer>> res = new ArrayList<>();
    private final List<Integer> path = new ArrayList<>();
    private int[] nums;

    List<List<Integer>> subsetsWithDup(int[] nums) {
        this.nums = nums.clone();
        Arrays.sort(this.nums); // equal values become neighbours
        res.clear();
        dfs(0);
        return res;
    }

    private void dfs(int start) {
        res.add(new ArrayList<>(path)); // copy: path keeps changing
        for (int i = start; i < nums.length; i++) {
            if (i > start && nums[i] == nums[i - 1]) continue; // already tried at this level
            path.add(nums[i]);
            dfs(i + 1);
            path.remove(path.size() - 1); // undo the choice
        }
    }
}
Go
import "sort"

func subsetsWithDup(nums []int) [][]int {
	nums = append([]int(nil), nums...)
	sort.Ints(nums) // equal values become neighbours
	var res [][]int
	var path []int
	var dfs func(start int)
	dfs = func(start int) {
		res = append(res, append([]int(nil), path...)) // copy: path keeps changing
		for i := start; i < len(nums); i++ {
			if i > start && nums[i] == nums[i-1] {
				continue // this value was already tried at this level
			}
			path = append(path, nums[i])
			dfs(i + 1)
			path = path[:len(path)-1] // undo the choice
		}
	}
	dfs(0)
	return res
}

Common variants

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

Variant matrix: each cell shows the line or two that decide it
Distinct · once eachRepeats · once eachDistinct · reusable
SubsetsPick or skip: two branches per indexdfs(i + 1) # skip nums[i] dfs(i + 1) # take nums[i]dfs(i + 1); // skip nums[i] dfs(i + 1); // take nums[i]dfs(i + 1); // skip nums[i] dfs(i + 1); // take nums[i]dfs(i + 1) // skip nums[i] dfs(i + 1) // take nums[i]Main templateif i > start and nums[i] == nums[i - 1]:if (i > start && nums[i] == nums[i - 1]) continue;if (i > start && nums[i] == nums[i - 1]) continue;if i > start && nums[i] == nums[i-1] {

A subset that may repeat a number without limit has infinitely many answers, so this cell has no program; add a sum or size limit and it becomes Combinations · reusable.

CombinationsCombinations: choose from start on, prune short branchesfor x in range(start, n - (k - len(path)) + 2):for (int x = start; x <= n - (k - (int)path.size()) + 1; x++) {for (int x = start; x <= n - (k - path.size()) + 1; x++) {for x := start; x <= n-(k-len(path))+1; x++ {Combinations with duplicates: skip equal values on a levelif i > start and nums[i] == nums[i - 1]: dfs(i + 1, remain - nums[i])if (i > start && nums[i] == nums[i - 1]) continue; dfs(i + 1, remain - nums[i]);if (i > start && nums[i] == nums[i - 1]) continue; dfs(i + 1, remain - nums[i]);if i > start && nums[i] == nums[i-1] { dfs(i+1, remain-nums[i])Combinations with reuse: recurse on the same indexdfs(i, remain - nums[i])dfs(i, remain - nums[i]);dfs(i, remain - nums[i]);dfs(i, remain-nums[i])
PermutationsPermutations: a used array marks placed elementsif used[i]:if (used[i]) continue;if (used[i]) continue;if used[i] {Permutations with duplicates: equal values in input orderif used[i] or (i > 0 and nums[i] == nums[i - 1] and not used[i - 1]):if (used[i] || (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]))if (used[i] || (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]))if used[i] || (i > 0 && nums[i] == nums[i-1] && !used[i-1]) {

Drop the used check so every level chooses from all elements, and record at length k: n^k sequences in all. LC 17 is the same shape with a different set of letters per level.

Pick or skip: two branches per indexO(n · 2^n) time · O(n) recursion depth

With distinct elements and every subset wanted, the plainest shape branches twice at each index (skip it, take it), and reaching the end yields one subset. LC 78 (Subsets) and LC 784 (Letter Case Permutation) have this shape.

Python
def subsets(nums: list[int]) -> list[list[int]]:
    """Every subset of distinct nums."""
    res, path = [], []

    def dfs(i: int) -> None:
        if i == len(nums):
            res.append(path[:])  # one leaf per subset
            return
        dfs(i + 1)  # skip nums[i]
        path.append(nums[i])
        dfs(i + 1)  # take nums[i]
        path.pop()

    dfs(0)
    return res
C++
// Every subset of distinct nums.
vector<vector<int>> subsets(const vector<int>& nums) {
    vector<vector<int>> res;
    vector<int> path;
    function<void(int)> dfs = [&](int i) {
        if (i == (int)nums.size()) {
            res.push_back(path);  // one leaf per subset
            return;
        }
        dfs(i + 1);  // skip nums[i]
        path.push_back(nums[i]);
        dfs(i + 1);  // take nums[i]
        path.pop_back();
    };
    dfs(0);
    return res;
}
Java
class Solution {
    private final List<List<Integer>> res = new ArrayList<>();
    private final List<Integer> path = new ArrayList<>();
    private int[] nums;

    // Every subset of distinct nums.
    List<List<Integer>> subsets(int[] nums) {
        this.nums = nums;
        res.clear();
        dfs(0);
        return new ArrayList<>(res);
    }

    private void dfs(int i) {
        if (i == nums.length) {
            res.add(new ArrayList<>(path)); // one leaf per subset
            return;
        }
        dfs(i + 1); // skip nums[i]
        path.add(nums[i]);
        dfs(i + 1); // take nums[i]
        path.remove(path.size() - 1);
    }
}
Go
// subsets returns every subset of distinct nums.
func subsets(nums []int) [][]int {
	var res [][]int
	var path []int
	var dfs func(i int)
	dfs = func(i int) {
		if i == len(nums) {
			res = append(res, append([]int(nil), path...)) // one leaf per subset
			return
		}
		dfs(i + 1) // skip nums[i]
		path = append(path, nums[i])
		dfs(i + 1) // take nums[i]
		path = path[:len(path)-1]
	}
	dfs(0)
	return res
}
Combinations: choose from start on, prune short branchesO(k · C(n, k)) time · O(k) recursion depth

For combinations of a fixed size k: each level picks from start onwards and records once k are chosen, and it stops as soon as too few numbers are left to finish. LC 77 (Combinations) and LC 216 (Combination Sum III) use this pruning.

Python
def combine(n: int, k: int) -> list[list[int]]:
    """Every k-number combination of 1..n, each in increasing order."""
    res, path = [], []

    def dfs(start: int) -> None:
        if len(path) == k:
            res.append(path[:])
            return
        for x in range(start, n - (k - len(path)) + 2):  # leave room for the rest
            path.append(x)
            dfs(x + 1)
            path.pop()

    dfs(1)
    return res
C++
// Every k-number combination of 1..n, each in increasing order.
vector<vector<int>> combine(int n, int k) {
    vector<vector<int>> res;
    vector<int> path;
    function<void(int)> dfs = [&](int start) {
        if ((int)path.size() == k) {
            res.push_back(path);
            return;
        }
        for (int x = start; x <= n - (k - (int)path.size()) + 1; x++) {  // leave room for the rest
            path.push_back(x);
            dfs(x + 1);
            path.pop_back();
        }
    };
    dfs(1);
    return res;
}
Java
class Solution {
    private final List<List<Integer>> res = new ArrayList<>();
    private final List<Integer> path = new ArrayList<>();
    private int n, k;

    // Every k-number combination of 1..n, each in increasing order.
    List<List<Integer>> combine(int n, int k) {
        this.n = n;
        this.k = k;
        res.clear();
        dfs(1);
        return new ArrayList<>(res);
    }

    private void dfs(int start) {
        if (path.size() == k) {
            res.add(new ArrayList<>(path));
            return;
        }
        for (int x = start; x <= n - (k - path.size()) + 1; x++) { // leave room for the rest
            path.add(x);
            dfs(x + 1);
            path.remove(path.size() - 1);
        }
    }
}
Go
// combine returns every k-number combination of 1..n, each in increasing order.
func combine(n, k int) [][]int {
	var res [][]int
	var path []int
	var dfs func(start int)
	dfs = func(start int) {
		if len(path) == k {
			res = append(res, append([]int(nil), path...))
			return
		}
		for x := start; x <= n-(k-len(path))+1; x++ { // leave room for the rest
			path = append(path, x)
			dfs(x + 1)
			path = path[:len(path)-1]
		}
	}
	dfs(1)
	return res
}
Combinations with reuse: recurse on the same indexExponential, governed by target / min · O(target / min) recursion depth

When a number may be picked again: recurse with i instead of i + 1. Sort first so that once a candidate exceeds the remaining target the loop breaks, since every later one is larger. LC 39 (Combination Sum) is this cell.

Python
def combination_sum(candidates: list[int], target: int) -> list[list[int]]:
    """Distinct positive candidates, each reusable: every multiset that sums to target."""
    nums = sorted(candidates)
    res, path = [], []

    def dfs(start: int, remain: int) -> None:
        if remain == 0:
            res.append(path[:])
            return
        for i in range(start, len(nums)):
            if nums[i] > remain:
                break  # sorted: every later candidate is too big as well
            path.append(nums[i])
            dfs(i, remain - nums[i])  # i, not i + 1: the same number may come again
            path.pop()

    dfs(0, target)
    return res
C++
// Distinct positive candidates, each reusable: every multiset that sums to target.
vector<vector<int>> combinationSum(vector<int> nums, int target) {
    sort(nums.begin(), nums.end());
    vector<vector<int>> res;
    vector<int> path;
    function<void(int, int)> dfs = [&](int start, int remain) {
        if (remain == 0) {
            res.push_back(path);
            return;
        }
        for (int i = start; i < (int)nums.size(); i++) {
            if (nums[i] > remain) break;  // sorted: every later candidate is too big as well
            path.push_back(nums[i]);
            dfs(i, remain - nums[i]);  // i, not i + 1: the same number may come again
            path.pop_back();
        }
    };
    dfs(0, target);
    return res;
}
Java
class Solution {
    private final List<List<Integer>> res = new ArrayList<>();
    private final List<Integer> path = new ArrayList<>();
    private int[] nums;

    // Distinct positive candidates, each reusable: every multiset that sums to target.
    List<List<Integer>> combinationSum(int[] candidates, int target) {
        nums = candidates.clone();
        Arrays.sort(nums);
        res.clear();
        dfs(0, target);
        return new ArrayList<>(res);
    }

    private void dfs(int start, int remain) {
        if (remain == 0) {
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = start; i < nums.length; i++) {
            if (nums[i] > remain) break; // sorted: every later candidate is too big as well
            path.add(nums[i]);
            dfs(i, remain - nums[i]); // i, not i + 1: the same number may come again
            path.remove(path.size() - 1);
        }
    }
}
Go
import "sort"

// combinationSum returns every multiset of the distinct, reusable candidates that sums to target.
func combinationSum(candidates []int, target int) [][]int {
	nums := append([]int(nil), candidates...)
	sort.Ints(nums)
	var res [][]int
	var path []int
	var dfs func(start, remain int)
	dfs = func(start, remain int) {
		if remain == 0 {
			res = append(res, append([]int(nil), path...))
			return
		}
		for i := start; i < len(nums); i++ {
			if nums[i] > remain {
				break // sorted: every later candidate is too big as well
			}
			path = append(path, nums[i])
			dfs(i, remain-nums[i]) // i, not i + 1: the same number may come again
			path = path[:len(path)-1]
		}
	}
	dfs(0, target)
	return res
}
Combinations with duplicates: skip equal values on a levelO(n · 2^n) time · O(n) recursion depth

With repeated numbers, each used once and no duplicate answers: sort, skip a value equal to the previous one on the same level, and recurse with i + 1. LC 40 (Combination Sum II) is this cell.

Python
def combination_sum2(candidates: list[int], target: int) -> list[list[int]]:
    """Each candidate used at most once; repeats in the input, no repeated answers."""
    nums = sorted(candidates)
    res, path = [], []

    def dfs(start: int, remain: int) -> None:
        if remain == 0:
            res.append(path[:])
            return
        for i in range(start, len(nums)):
            if nums[i] > remain:
                break
            if i > start and nums[i] == nums[i - 1]:
                continue  # this value was already tried at this level
            path.append(nums[i])
            dfs(i + 1, remain - nums[i])
            path.pop()

    dfs(0, target)
    return res
C++
// Each candidate used at most once; repeats in the input, no repeated answers.
vector<vector<int>> combinationSum2(vector<int> nums, int target) {
    sort(nums.begin(), nums.end());
    vector<vector<int>> res;
    vector<int> path;
    function<void(int, int)> dfs = [&](int start, int remain) {
        if (remain == 0) {
            res.push_back(path);
            return;
        }
        for (int i = start; i < (int)nums.size(); i++) {
            if (nums[i] > remain) break;
            if (i > start && nums[i] == nums[i - 1]) continue;  // already tried at this level
            path.push_back(nums[i]);
            dfs(i + 1, remain - nums[i]);
            path.pop_back();
        }
    };
    dfs(0, target);
    return res;
}
Java
class Solution {
    private final List<List<Integer>> res = new ArrayList<>();
    private final List<Integer> path = new ArrayList<>();
    private int[] nums;

    // Each candidate used at most once; repeats in the input, no repeated answers.
    List<List<Integer>> combinationSum2(int[] candidates, int target) {
        nums = candidates.clone();
        Arrays.sort(nums);
        res.clear();
        dfs(0, target);
        return new ArrayList<>(res);
    }

    private void dfs(int start, int remain) {
        if (remain == 0) {
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = start; i < nums.length; i++) {
            if (nums[i] > remain) break;
            if (i > start && nums[i] == nums[i - 1]) continue; // already tried at this level
            path.add(nums[i]);
            dfs(i + 1, remain - nums[i]);
            path.remove(path.size() - 1);
        }
    }
}
Go
import "sort"

// combinationSum2 uses each candidate at most once and returns no repeated answers.
func combinationSum2(candidates []int, target int) [][]int {
	nums := append([]int(nil), candidates...)
	sort.Ints(nums)
	var res [][]int
	var path []int
	var dfs func(start, remain int)
	dfs = func(start, remain int) {
		if remain == 0 {
			res = append(res, append([]int(nil), path...))
			return
		}
		for i := start; i < len(nums); i++ {
			if nums[i] > remain {
				break
			}
			if i > start && nums[i] == nums[i-1] {
				continue // this value was already tried at this level
			}
			path = append(path, nums[i])
			dfs(i+1, remain-nums[i])
			path = path[:len(path)-1]
		}
	}
	dfs(0, target)
	return res
}
Permutations: a used array marks placed elementsO(n · n!) time · O(n) space

When order matters, every level scans from the start and skips positions already used. LC 46 (Permutations) is this cell; LC 17 (Letter Combinations of a Phone Number) is the same skeleton with a new set of choices per level.

Python
def permute(nums: list[int]) -> list[list[int]]:
    """Every ordering of distinct nums."""
    res, path, used = [], [], [False] * len(nums)

    def dfs() -> None:
        if len(path) == len(nums):
            res.append(path[:])
            return
        for i, x in enumerate(nums):
            if used[i]:
                continue  # each element appears once per ordering
            used[i] = True
            path.append(x)
            dfs()
            path.pop()
            used[i] = False

    dfs()
    return res
C++
// Every ordering of distinct nums.
vector<vector<int>> permute(const vector<int>& nums) {
    vector<vector<int>> res;
    vector<int> path;
    vector<bool> used(nums.size(), false);
    function<void()> dfs = [&]() {
        if (path.size() == nums.size()) {
            res.push_back(path);
            return;
        }
        for (size_t i = 0; i < nums.size(); i++) {
            if (used[i]) continue;  // each element appears once per ordering
            used[i] = true;
            path.push_back(nums[i]);
            dfs();
            path.pop_back();
            used[i] = false;
        }
    };
    dfs();
    return res;
}
Java
class Solution {
    private final List<List<Integer>> res = new ArrayList<>();
    private final List<Integer> path = new ArrayList<>();
    private int[] nums;
    private boolean[] used;

    // Every ordering of distinct nums.
    List<List<Integer>> permute(int[] nums) {
        this.nums = nums;
        used = new boolean[nums.length];
        res.clear();
        dfs();
        return new ArrayList<>(res);
    }

    private void dfs() {
        if (path.size() == nums.length) {
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (used[i]) continue; // each element appears once per ordering
            used[i] = true;
            path.add(nums[i]);
            dfs();
            path.remove(path.size() - 1);
            used[i] = false;
        }
    }
}
Go
// permute returns every ordering of distinct nums.
func permute(nums []int) [][]int {
	var res [][]int
	var path []int
	used := make([]bool, len(nums))
	var dfs func()
	dfs = func() {
		if len(path) == len(nums) {
			res = append(res, append([]int(nil), path...))
			return
		}
		for i, x := range nums {
			if used[i] {
				continue // each element appears once per ordering
			}
			used[i] = true
			path = append(path, x)
			dfs()
			path = path[:len(path)-1]
			used[i] = false
		}
	}
	dfs()
	return res
}
Permutations with duplicates: equal values in input orderO(n · n!) time · O(n) space

With repeats in the input and no repeated orderings: sort, and let equal values be placed only in input order, skipping one while the equal value before it is unused. LC 47 (Permutations II) and LC 1079 (Letter Tile Possibilities) rely on that one line.

Python
def permute_unique(nums: list[int]) -> list[list[int]]:
    """Every distinct ordering when nums has repeats."""
    nums = sorted(nums)
    res, path, used = [], [], [False] * len(nums)

    def dfs() -> None:
        if len(path) == len(nums):
            res.append(path[:])
            return
        for i in range(len(nums)):
            if used[i] or (i > 0 and nums[i] == nums[i - 1] and not used[i - 1]):
                continue  # equal values are placed in input order only
            used[i] = True
            path.append(nums[i])
            dfs()
            path.pop()
            used[i] = False

    dfs()
    return res
C++
// Every distinct ordering when nums has repeats.
vector<vector<int>> permuteUnique(vector<int> nums) {
    sort(nums.begin(), nums.end());
    vector<vector<int>> res;
    vector<int> path;
    vector<bool> used(nums.size(), false);
    function<void()> dfs = [&]() {
        if (path.size() == nums.size()) {
            res.push_back(path);
            return;
        }
        for (size_t i = 0; i < nums.size(); i++) {
            if (used[i] || (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]))
                continue;  // equal values are placed in input order only
            used[i] = true;
            path.push_back(nums[i]);
            dfs();
            path.pop_back();
            used[i] = false;
        }
    };
    dfs();
    return res;
}
Java
class Solution {
    private final List<List<Integer>> res = new ArrayList<>();
    private final List<Integer> path = new ArrayList<>();
    private int[] nums;
    private boolean[] used;

    // Every distinct ordering when nums has repeats.
    List<List<Integer>> permuteUnique(int[] nums) {
        this.nums = nums.clone();
        Arrays.sort(this.nums);
        used = new boolean[nums.length];
        res.clear();
        dfs();
        return new ArrayList<>(res);
    }

    private void dfs() {
        if (path.size() == nums.length) {
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (used[i] || (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]))
                continue; // equal values are placed in input order only
            used[i] = true;
            path.add(nums[i]);
            dfs();
            path.remove(path.size() - 1);
            used[i] = false;
        }
    }
}
Go
import "sort"

// permuteUnique returns every distinct ordering when nums has repeats.
func permuteUnique(input []int) [][]int {
	nums := append([]int(nil), input...)
	sort.Ints(nums)
	var res [][]int
	var path []int
	used := make([]bool, len(nums))
	var dfs func()
	dfs = func() {
		if len(path) == len(nums) {
			res = append(res, append([]int(nil), path...))
			return
		}
		for i := range nums {
			if used[i] || (i > 0 && nums[i] == nums[i-1] && !used[i-1]) {
				continue // equal values are placed in input order only
			}
			used[i] = true
			path = append(path, nums[i])
			dfs()
			path = path[:len(path)-1]
			used[i] = false
		}
	}
	dfs()
	return res
}

Why it works

  1. Each node of the search tree is a partial solution; choose, recurse, undo guarantees path is restored when a child returns, so sibling branches never see each other's state.
  2. Choosing combinations from start onwards forces indexes to increase, and each combination has exactly one increasing order, so each is generated exactly once.
  3. The dedupe test i > start && nums[i] == nums[i−1]: after sorting, equal values sit together, and only the first of them branches on a level, because its subtree already contains every result the later copies could produce.

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.

中文
枚举子集、组合、排列,我用回溯三步:选择、递归、撤销。path 是整个搜索共用的一个缓冲区,撤销保证兄弟分支互不干扰。组合从 start 往后选,强制下标递增,每个组合只出现一次;有重复元素就先排序,同一层跳过和前一个相同的值。复杂度和答案数量同阶,比如子集是 O(n · 2^n)。
English
For subsets, combinations and permutations I backtrack in three moves: choose, recurse, undo. path is one buffer shared by the whole search, and undoing keeps sibling branches independent. Combinations pick from start onward, so indexes increase and each combination appears once; with duplicates I sort and skip a value equal to the previous one on the same level. The cost matches the output size, for example O(n · 2^n) for subsets.

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

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

4 questions
  1. Backtracking generates every subset of n distinct items, copying each one out as a list. Total time?
  2. To list unique permutations of [1, 1, 2]: sort, then at each position skip nums[i] when nums[i] == nums[i-1] and nums[i-1] is not in use. What does this rule guarantee?
  3. What is the time complexity of this code (n = len(a), tightest bound)?
    def subsets(a):
        out = []
    
        def go(i, cur):
            if i == len(a):
                out.append(cur[:])
                return
            go(i + 1, cur)
            cur.append(a[i])
            go(i + 1, cur)
            cur.pop()
    
        go(0, [])
        return out
  4. What is the time complexity of this code (n = len(a), tightest bound)?
    def perms(a):
        out = []
        used = [False] * len(a)
    
        def go(cur):
            if len(cur) == len(a):
                out.append(cur[:])
                return
            for i in range(len(a)):
                if not used[i]:
                    used[i] = True
                    cur.append(a[i])
                    go(cur)
                    cur.pop()
                    used[i] = False
    
        go([])
        return out

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 subsets_with_dup(nums: list[int]) -> list[list[int]]:

Practice by stage

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

Foundation 5

#ProblemApproachRating
78SubsetsEnumerate subsets by choosing or skipping each element, making exactly one decision per position.
77CombinationsEnumerate fixed-size combinations and prune when too few positions remain.
46PermutationsEnumerate permutations with usage markers, distinguishing path order from the set of chosen elements.
17Letter Combinations of a Phone NumberExpand character choices position by position to practice a multilevel decision tree.
784Letter Case PermutationChoose letter case character by character, branching for letters but taking only one branch for digits.Rating 1342

Core 7

#ProblemApproachRating
90Subsets IISort and skip equal values at the same recursion level to avoid duplicate subsets.
47Permutations IIHandle duplicates in permutations, distinguishing same-level deduplication from reuse across recursion levels.
39Combination SumControl the starting index to allow repeated choices without producing different orders of the same combination.
40Combination Sum IIUse each candidate position at most once, combining sorting, pruning, and same-level deduplication.
216Combination Sum IIIConstrain the number of choices, their sum, and the increasing candidate range simultaneously.
1079Letter Tile PossibilitiesEnumerate distinct nonempty sequences through character frequencies so repeated letters do not cause double-counting.Rating 1741
491Non-decreasing SubsequencesEnumerate nondecreasing subsequences in original index order and deduplicate choices with a set at each recursion level.