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, which fits within a 1-second limit. At 30 items, 2³⁰ ≈ 10⁹times out. This page explains the difference between n!, 2ⁿ, and C(n,k) and where each appears in DSA.

By the numbers

n2ⁿC(n, n/2)n!Judge limit (≈10⁸)
101,0242523.6Mfits
1532,7686,4351.3T2ⁿ ok, n! times out
201M184,7562.4·10¹⁸2ⁿ ok, n! infeasible
2533M5.2Minfeasible2ⁿ tight, C(n,k) ok
301.07B155Minfeasible2ⁿ times out, C(n,k) tight

In short: 2ⁿ works for n ≤ 20 and times out for n ≥ 30. n! is already infeasible at n ≥ 15. C(n, k) at k ~n/2 is ~√(πn/2) smaller than 2ⁿ, yet 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 shows why backtracking problems carry n ≤ 15 constraints.

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

← All math topics →