Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Backtracking & Recursion

Subsets / Permutations / Combinations

O(2ⁿ) · O(n!)

At each element choose include/exclude (subsets) or fix-then-recurse on the rest (permutations); collect at the leaves.

  1. 1Learnthe lesson(you are here)
  2. 2Guidedwatch it run, line by line(not yet)
  3. 3Practisethe path, or the climb(not yet)
  4. 4Revisereviews on schedule(not yet)
Start the lesson
UnlocksBacktrackingBitmask DPMeet in the MiddleDivide and Conquer (merge-sort counting)
0%
mastery
0/10 solved
IdeaPracticeTemplatePitfalls

Recognise it

The signal

"Return all subsets / combinations / permutations" with small n (≤ ~15–20); the output itself is exponential.

  1. 1Brute force

    This is the brute force; the skill is generating each object exactly once.

  2. 2The observation

    Duplicates and wasted branches: sort + skip equal siblings, start index for combinations.

  3. 3Why it works

    The recursion path is the partial object; every leaf is produced exactly once.

Reach for it when

  • +You must produce every subset, combination, or permutation — the full set, not a count or a single best.
  • +n is small (the output itself is exponential, so n ≤ ~15–20).
  • +The answer is a list of lists / all valid configurations.

Not when

  • ×Only the count of ways or the single best is askeduse DP or greedy, not enumeration
  • ×n is large (≥ ~25), so 2ⁿ is hopelessuse Find structure: DP or math
  • ×A goal must be satisfied incrementally with heavy pruninguse Prune-as-you-go backtracking

Intuition

When a prompt says "return ALL subsets / combinations / permutations", it's asking you to enumerate a tree of choices. The tool is recursion that builds a partial answer, then undoes its last move — backtracking.

Read the full intuition

The cleanest mental model is a decision tree. For subsets of [1,2,3]: at element 1 you branch include or exclude; same at 2, same at 3. 2³ = 8 leaves = 8 subsets. You walk this tree depth-first, carrying a "current path", and snapshot the path whenever you reach a node you care about.

The universal shape:

Text
choose an option  →  recurse deeper  →  un-choose (backtrack)

That "un-choose" (pop the last element) is what lets one list be reused for the whole tree instead of copying at every branch.

Three flavours, same skeleton:

  • Subsets: at each index, recurse with and without it (or: for-loop picking a start index, record every node).
  • Combinations (pick k, order doesn't matter): loop from a start index forward so you never reuse earlier elements → no duplicates like [1,2]/[2,1].
  • Permutations (order matters): no start; instead a used[] flag, looping over all elements each level.

Key idea

The single most important rule: append a copy of the path when recording (path[:] / new array), never the live list — it keeps mutating under you.

Why it costs what it costs

Time O(n·2ⁿ) subsets, O(n·n!) perms. there are 2ⁿ subsets / n! permutations, and copying each path of length up to n costs O(n).

Space O(n). recursion depth and the path are both O(n) (output not counted).

Practice

Next · Foundation

Subsets

2^n leaves; iterative bitmask version is equivalent.

0/10 solved
  • SubsetsFoundationFoundationMeta, AmazonMedium
  • CombinationsApply it · Fixed size k.Apply itGoogle, MetaMedium
  • PermutationsOne change · Order matters.One changeMeta, AmazonMedium
  • Subsets IITwists · Input has duplicates.TwistsMeta, AmazonMedium
  • Permutations IITwists · Permutations with duplicates.TwistsMedium
  • Combination SumBranches · Elements reusable.BranchesAmazon, MetaMedium
  • Letter Combinations of a Phone NumberBranches · Cartesian product of choice lists.BranchesAmazon, UberMedium
  • Partition to K Equal Sum SubsetsMastery checkMastery checkAmazon, CitadelMedium
  • Creating StringsCSESEasy
  • Apple DivisionCSESEasy

Pitfalls

Classic bugs

  • !Appending the live list instead of a copy — every saved answer ends up identical (usually empty).
  • !Forgetting to pop after recursing — path state leaks into sibling branches.
  • !Use a start index for combinations or used[] for permutations, not both.
  • !Duplicates (Subsets II): sort, then skip nums[i]==nums[i-1] only at the same tree level, not globally.
  • !Combination Sum (reuse) recurses with i; Combination Sum II (no reuse) recurses with i+1 and dedupes.

Looks like it, isn't

  • Combination Sum IV needs Unbounded Knapsack
    Why
    Only the count is asked and order matters: dp over amounts with amount as outer loop.
  • Find the K-Sum of an Array needs K-way Merge
    Why
    Enumerating subsets is 2n. Sort |a| and pop k times from a frontier heap with the 'extend / replace last' successor rule. source ↗
Go deepervariants and techniques · resources

Variants and techniques

  • Subsets (power set)Record at every node; loop from start, recurse i+1. Subsets.
  • Subsets / combos with duplicatesSort, then if i>start and nums[i]==nums[i-1]: continue to skip repeats per level. Subsets II, Combination Sum II.
  • PermutationsNo start index; used[] flags; record at full length. Permutations, Permutations II.
  • Combination Sum (reuse allowed)Recurse with i (same element again) and a shrinking target; prune when target<0. Combination Sum.
  • Mapping enumerationDigits→letters product via index-based recursion. Letter Combinations of a Phone Number.

Resources

  • Complete Search with RecursionUSACO Guide · course
  • Recursion I explore cardLeetCode · course
  • Recursion cheatsheetTech Interview Handbook · article
  • General approach to backtracking questionsLeetCode discuss · article
  • Competitive Programmer's HandbookAntti Laaksonen · book
K-way MergeBacktracking
TodayReviewPatternsProblems

Template · clean C++, Java and Python to revise from

Start the free 7-day trial