Question Bank

Recursion and Backtracking

Difficulty: Medium

Four prompts on the recurse-mutate-undo pattern: subsets, permutations, and combinations. Includes one trace and one bug hunt.

Question Bank
/

Recursion and Backtracking

Recursion and Backtracking

Four prompts on the recurse-mutate-undo pattern: subsets, permutations, and combinations. Includes one trace and one bug hunt.

Question Bank
Medium
JavaScript
4 questions
recursion
backtracking
algorithms
interview-prep

427 views

10

Implement subsets(nums) returning all 2^n subsets of nums (no duplicates assumed). Use recursion with the include / exclude branch.

Examples

Example 1:

Input: nums = [1, 2, 3]
Output: 8 subsets, for example [[], [3], [2], [2, 3], [1], [1, 3], [1, 2], [1, 2, 3]]
Explanation: At each index, recurse twice: exclude nums[i], then include nums[i]. The 2^n leaves are the subsets. O(n * 2^n) to emit copies, O(n) stack.