Coding Interview Questions

Backtracking Framework: Permutations, Combinations, Subsets

Describe your backtracking template. How do permutations, combinations, and subsets differ?

Why Interviewers Ask This

Backtracking questions are common and interviewer-friendly. One template handles most of them.

How to Answer

  1. 1

    Template: at each decision point, try each valid choice → recurse → undo (pop). Always triple: "make choice / recurse / undo".

  2. 2

    Subsets: include or exclude each element. 2^n outputs. Collect path at every node.

  3. 3

    Combinations: like subsets but with size k constraint (skip branches where path.size > k, or limited by the start pointer).

  4. 4

    Permutations: order matters. Maintain a used[] set or swap-in-place. n! outputs.

  5. 5

    Pruning: sort input and skip duplicates, cutoff when remaining can't meet target (subset sum), bound cost against best-so-far.

Sample Answer

One template: `void dfs(path, state) { if (terminal) { record path; return } for (choice in choices(state)) { apply(choice); dfs(path+choice, nextState); undo(choice); } }`. Subsets collect path every call (no terminal gate), permutations use a visited[] to skip used elements, combinations start the inner loop from i+1 instead of 0. For duplicates I sort input and skip `if i > start && nums[i]==nums[i-1]`. Pruning is what separates passing from TLE — in subset-sum I cut when path-sum already exceeds target; in N-queens I maintain diagonals in sets for O(1) validity check. The recursion tree shape tells me the worst case: 2^n for subsets, n! for permutations.

Pro Tips

  • Always undo explicitly — easier to reason about than copying the path at every recurse.

  • Visited[] beats removing from list — O(1) vs O(n) per operation.

  • HireMe AI (即答侠) has one-page cheat sheets for subset/permutation/combination with duplicate-handling templates.

Frequently Asked Questions

Backtracking vs DFS?

Backtracking IS DFS, with an explicit undo step so we can explore the next choice. DFS is the broader term.

When to prune early?

Any time a monotonic bound proves the rest of a branch can't improve the best answer. Sorting input first often enables pruning.

Worried About Going Blank in Your Interview?

HireMe AI listens to your interview in real-time, detects questions, and generates instant answer suggestions — so you never freeze up again.

Try HireMe AI Free