Pattern #24
Combinations
Important interview questions, thinking patterns, nCr formulas, forward start index navigation, reusable vs non-reusable elements, and Go rules.
Must Solve
15 core questions — solve these first.
- 1.CombinationsChoose K items from N using start index (nCr)medium
- 2.Combination SumReusable element choice (pass index i into dfs)medium
- 3.Combination Sum IISingle-use element choice (pass index i+1) + skip duplicatesmedium
- 4.Combination Sum IIIChoose K digits from 1-9 summing to target Nmedium
- 5.SubsetsTake or Skip power set generationmedium
- 6.Subsets IISort input + skip same-level duplicatesmedium
- 7.Generate ParenthesesOpen and close bracket combination countmedium
- 8.Letter Combinations of a Phone NumberDigit string mapping combination searchmedium
- 9.Palindrome PartitioningSub-string palindrome partition combinationsmedium
- 10.Restore IP AddressesPartition string into 4 valid 0-255 IP segment combinationsmedium
- 11.Partition Equal Subset SumTarget sum = totalSum/2 combination search or DPmedium
- 12.Partition to K Equal Sum SubsetsK subset sum buckets + pruningmedium
- 13.Matchsticks to Square4-side sum partitioning + sort descendingmedium
- 14.N-QueensQueen placement combinations on NxN chessboardhard
- 15.Word SearchGrid DFS 4-directional path combinationsmedium
Also Important
8 more questions worth practicing.
- 16.Letter Tile PossibilitiesUnique character combination sequencesmedium
- 17.Beautiful ArrangementDivisibility rule combination checkmedium
- 18.Fair Distribution of CookiesDistribution of N cookie bags to K childrenmedium
- 19.Maximum Length of a Concatenated String with Unique CharactersBitmask / Subset unique char concatenationmedium
- 20.Split a String Into the Max Number of Unique SubstringsHashSet seen unique substrings recursionmedium
- 21.Count Number of Maximum Bitwise-OR SubsetsBitwise OR combination subsets countingmedium
- 22.Combination Sum IVDP permutation sum count (order matters!)medium
- 23.Factor CombinationsGenerate all factor combinations of integer Nmedium
How to Think
- Need choose K items?Combination (nCr)
- Order does NOT matter?Combination ([1,2] == [2,1])
- Need all possible groups?Backtracking
- Need reach target using choices?Combination Sum
- Input has duplicates?Sort + skip same-level duplicates
Go Combinations Template (Choose K from N)
Standard Combinations Template in Go
func combine(n int, k int) [][]int {
results := [][]int{}
path := []int{}
var dfs func(start int)
dfs = func(start int) {
if len(path) == k {
copyPath := append([]int(nil), path...)
results = append(results, copyPath)
return
}
// Optimization Pruning: Stop if remaining elements (n - i + 1) < needed (k - len(path))
for i := start; i <= n - (k - len(path)) + 1; i++ {
path = append(path, i)
dfs(i + 1) // Move start forward strictly to avoid reversed duplicates like [2, 1]
path = path[:len(path)-1] // Undo
}
}
dfs(1)
return results
}👉 Total Time: O(K × nCk) | Space: O(K) (Recursion depth = K)
Reusable vs Non-Reusable Elements
dfs(i + 1) // Move start to next index!Used for standard Combinations and Combination Sum II where each number can be picked at most once.
dfs(i) // Keep start index at current i!Used for Combination Sum I where the same number can be chosen an unlimited number of times!
Pruning Optimizations
Pruning stops exploring impossible recursion branches early before wasting CPU cycles:
If all numbers are positive and sum > target, stop recursion immediately!
If remaining elements (n - i + 1) < (k - len(path)), stop loop because it is impossible to reach size K!
Order Does NOT Matter! → [1, 2] == [2, 1] (Use start index to avoid reverse duplicates)
Reuse Elements? → Call dfs(i)
Single-Use Elements? → Call dfs(i + 1)
Prune Invalid Branch → Stop if sum > target or remaining elements < needed💡 Golden Rule: "Choose an item, move forward, and never generate the same group in a different order."
Common Interview Mistakes
Generating both [1, 2] and [2, 1] for combinations. Always use start index to move forward strictly!
Passing dfs(i + 1) when element reuse is allowed, or passing dfs(i) when element reuse is prohibited.
Adding item to path but forgetting path = path[:len(path)-1] pops state after recursion returns.
Saving path without copy causes later backtracking pops to mutate saved combination results!
Interview Rules
- 1. Choose K items? → Combinations (nCr)
- 2. Order does NOT matter? → Combination (
[1, 2] == [2, 1]) - 3. Move forward strictly →
startindex avoids reversed duplicates - 4. Cannot reuse elements? → Recurse with
i + 1 - 5. Can reuse elements? → Recurse with
i - 6. Target sum reached? → Save answer
- 7. Duplicate input? → Sort first + skip same-level duplicates
- 8. Overall Complexity →
O(K × nCk) time, O(K) space
Small Rules
- Rule 1: Order does not matter in combinations.
- Rule 2: Use start index to avoid generating reversed duplicate groups.
- Rule 3: Base case for choosing K items is len(path) == k.
- Rule 4: Base case for target sum is sum == target.
- Rule 5:Stop branch early if remaining elements (n - i + 1) < needed (k - len(path)).
Production Thinking
Incident Response Team Building → Choose 3 engineers from 10 (Order doesn't matter) = 10C3 = 120 team combinations
Feature Variant Selection → Select exactly 3 features out of 10 for A/B testing experiment group
Replica Server Selection → Choose 3 replica nodes out of 20 available server instances
Test Configuration Groups → Test every combination group of 2 enabled feature flags across system
Production Warning → Combination growth: Choosing 10 from 20 = 20C10 = 184,756 combinations! Prune and constrain production searches.
Remember This
Combination → Order does NOT matter
Choose K → Backtracking
Avoid reversed dups → Start index
Cannot reuse → i + 1
Can reuse → i
Duplicates → Sort + skip same level
Target reached → Save
Impossible → Prune💡 Golden Rule: "Choose an item, move forward, and never generate the same group in a different order."