Skip to content
ΣDSA Patterns
Menu
Language

Foundations

Combinatorics basics

Permutations n!, combinations, subsets 2ⁿ - visualized with small n.

Question: how many operations to enumerate all subsets of 20 items?

2²⁰ = 1,048,576. Survivable. But 30 items is 2³⁰ ≈ 10⁹ and you're guaranteed to time out. This page unpacks the gap between n!, 2ⁿ, and C(n,k) and where each one drives a DSA pattern.

By the numbers

n2ⁿC(n, n/2)n!Judge limit (≈10⁸)
101,0242523.6Msurvives
1532,7686,4351.3T2ⁿ ok, n! dies
201M184,7562.4·10¹⁸2ⁿ ok, n! impossible
2533M5.2Mblows up2ⁿ tight, C(n,k) ok
301.07B155Mblows up2ⁿ dies, C(n,k) tight

One line: 2ⁿ survives for n ≤ 20, dies for n ≥ 30. n! is already impossible at n ≥ 15. C(n, k) at k ~n/2 is ~√(πn/2) smaller than 2ⁿ but still exponential.

Where each comes from

n! (permutations)

n items: first has n positions, second n-1, … → n · (n-1) · … · 1 = n!. Enumerating all permutations (LC 46, 47) costs this. Backtracking in its naive form is exactly this; without pruning you walk every leaf.

2ⁿ (subsets)

Each item is included or excluded, two choices → 2 · 2 · … · 2 = 2ⁿ. Enumerating all subsets (LC 78, 90) or subset DP (LC 416, 494) costs this. n ≤ 20 gives ~1M leaves you can actually walk; that's why subset DP has the n ≤ 20 rule.

C(n, k) (combinations)

Choose k from n: n! / (k! · (n-k)!). Generating combinations (LC 39, 77) produces this many leaves. Maximized at k ~n/2, where it's ~2ⁿ / √(πn/2): smaller than 2ⁿ but still exponential.

Trap: "C(n, k) is polynomial, 2ⁿ is exponential"

Wrong. C(n, n/2) is exponential: C(20,10) = 184,756,C(30,15) = 155M. For fixed k, C(n,k) = O(nᵏ) is polynomial, but if k grows with n it's exponential. So "combinations are polynomial" is misleading; it depends on how k relates to n.

Where to go next

Exercise

Set the slider to n = 10. Predict the n!, 2ⁿ, and C(n, n/2) values. Now move ton = 15: how many times did n! grow? How many times did 2ⁿ? This concretizes why backtracking problems carry n ≤ 15 constraints.

n = 8
40.3k8!70C(8,4)2562^8

← All math topics →