Starting from a finite set, we can construct pairs, sequences, subsets, and orderings. For each construction, these notes explain what counts as a distinct result, how many results exist, and the time and storage required to generate them.
Before counting, decide what makes two objects distinct: whether order matters and whether elements may be reused. Keep those rules fixed throughout the problem.
Let a finite set be:
A = {a, b, c}
|A| = n = 3
Unless stated otherwise,
Almost everything below is about creating new sets of objects from A, then counting how many objects there are, then generating them efficiently.
This is the same move you do in programming all the time, turning a small input into a space of candidates. If the candidate space is small, brute force can work. If it’s huge (hello,
When you see “choose one thing from here and one thing from there,” you’re in Cartesian-product land. It’s the formal version of nested loops: for each
The Cartesian product
A × B = {(x, y) : x ∈ A, y ∈ B}
Example diagram
Let:
A = {a, b, c}
B = {0, 1}
Then:
A × B =
(a,0) (a,1)
(b,0) (b,1)
(c,0) (c,1)
“grid view”:
B
0 1
A +-----+-----+
a | a,0 | a,1 |
+-----+-----+
b | b,0 | b,1 |
+-----+-----+
c | c,0 | c,1 |
+-----+-----+
Do remember these are ordered pairs,
If
|A × B| = n·m
This is the foundation of:
- counting multi-step choices (“choose x then choose y”)
- building tuples (records, coordinates)
- generating combinations/permutations via sequences (see below)
This shows up constantly in real code: if you ever wrote two nested loops, joined two tables, or enumerated coordinate pairs on a grid, you were living in
To enumerate all pairs you must output
- Time:
$\Theta(n\cdot m)$ - Space:
$\Theta(1)$ extra (if streaming) or$\Theta(n\cdot m)$ if storing
A practical do/don’t: do stream results when possible (generate and consume immediately), and don’t store the full product unless you truly need random access, memory can become your bottleneck before time does.
If Cartesian products feel like “two-loop land,” the power set is “every possible on/off choice.” This is where problems become exponential because you’re not picking one item, you’re deciding for each item whether it’s included.
First step: Decide whether you must list every subset or only count or optimize over them. Listing costs
$\Theta(n \cdot 2^n)$ and is realistic up to about$n = 20$ . If you only need a count or a best value, look for a formula or a dynamic program instead.
The power set
For A={a,b,c}:
𝒫(A) = {
∅,
{a}, {b}, {c},
{a,b}, {a,c}, {b,c},
{a,b,c}
}
Subset lattice (Boolean lattice):
{a,b,c}
/ | \
{a,b} {a,c} {b,c}
| \ / \ / |
| / \ / \ |
{a} {b} {c}
\ | /
∅
The power set is the search space behind “try all subsets” algorithms, feature selection, subset sum, knapsack-style brute force, and lots of graph subset problems. The lattice diagram is the map of that search space.
If
|𝒫(A)| = 2^n
Why? Each element has two states: “in” or “out”.
Bitmask picture (n=3):
a b c subset
0 0 0 ∅
1 0 0 {a}
0 1 0 {b}
0 0 1 {c}
1 1 0 {a,b}
1 0 1 {a,c}
0 1 1 {b,c}
1 1 1 {a,b,c}
A do/don’t that saves headaches: do think “bitmask = subset” whenever you need to generate subsets efficiently, and don’t try to be “clever” by skipping the output cost, if the problem truly needs all subsets,
To enumerate all subsets, you must output
- Time:
$\Theta(n\cdot 2^n)$ if you build each subset explicitly (each subset may cost up to$n$ to construct) - Space:
$\Theta(n)$ recursion/bitmask state (streaming) or$\Theta(n\cdot 2^n)$ if storing all
The big idea: output size dominates. If you’re generating all subsets, you’re not “being slow”, you’re paying the bill for the number of results you asked to print.
Number the elements mask from mask is set, which you test with (mask >> i) & 1. Looping over all masks is the iterative answer to LeetCode 78 Subsets and needs no recursion at all.
A second iterative style starts with [[]] and, for each new element, appends a copy of every existing subset with that element added. Both produce all
def subsets(nums):
n = len(nums)
result = []
for mask in range(1 << n):
result.append([nums[i] for i in range(n) if (mask >> i) & 1])
return resultThe same loop solves LeetCode 784 Letter Case Permutation (a mask over the letter positions picks which letters are uppercase, giving
Time is 2^n in Python or C, where ^ is XOR; write 1 << n.
Sometimes you already have a set mask and need every subset of it, for example in DP over subsets where a state is split into two parts. The trick sub = (sub - 1) & mask jumps straight to the next smaller submask and skips every integer that has a bit outside mask.
sub = mask
while True:
process(sub)
if sub == 0:
break
sub = (sub - 1) & maskA mask with while sub > 0 silently skips the empty submask, and forgetting the break loops forever because (0 - 1) & mask is mask again.
LeetCode 89 Gray Code asks for all i ^ (i >> 1).
The reflect construction explains why it works. Take the list for
def gray_code(n):
return [i ^ (i >> 1) for i in range(1 << n)]Time is i ^ (i << 1), which produces values outside the
Combinations are how you take the power set and say: “Okay, cool, but I only want subsets of a specific size.” This is a common “make the search space manageable” move: instead of every subset, you focus on one level of the lattice.
First step: Confirm that order really does not matter and that each element can be picked at most once. Then decide whether you need the actual groups or only how many there are, and check how large
$\binom{n}{k}$ can get before choosing an integer type or a modulus.
A
The set of all
{ S ⊆ A : |S| = k }
Counting (binomial coefficient)
If
C(n,k) = "n choose k" = n! / (k!(n-k)!)
In standard notation, this is
Do use
Combinations form a level in the power-set lattice.
For A={a,b,c}, k=2:
level k=2: {a,b} {a,c} {b,c}
Power set is all combinations across all k:
2^n = |𝒫(A)| = Σ_{k=0..n} C(n,k)
Proper math:
To enumerate all
- Time:
$\Theta(k \cdot C(n,k))$ (each output has$k$ items) - Space:
$O(k)$ working storage for a generator that recurses over chosen positions. A literal take/skip recursion over all$n$ input positions can instead need$O(n)$ stack space.
Common methods:
- recursive backtracking (“take / skip”)
- iterative lexicographic combination generation
- bitmask “next k-bit” tricks
One practical tip: do pick your generation method based on what you need downstream (lexicographic order? Streaming? Constant extra memory?), and don’t assume “combinations are always small”,
LeetCode 77 Combinations is usually solved by backtracking with a start index: after choosing position i, the next choice starts at i + 1, so no element is reused and no group appears in two orders. Prune by stopping the loop once too few elements remain to fill the group. The general backtracking template is in the backtracking note.
The iterative alternative works on a sorted list of
def next_combination(c, n):
k = len(c)
i = k - 1
while i >= 0 and c[i] == n - k + i: # c[i] is already at its maximum
i -= 1
if i < 0:
return False # c was the last combination
c[i] += 1
for j in range(i + 1, k):
c[j] = c[j - 1] + 1
return TrueEach step costs i instead of i + 1 to the next call, which allows reuse and turns combinations into multisets.
Computing
Pascal's rule
def pascal_row(n):
row = [1] * (n + 1)
for i in range(1, n + 1):
for j in range(i - 1, 0, -1): # right to left keeps old values
row[j] += row[j - 1]
return rowThe multiplicative formula computes a single value in r = 1 and for r = r * (n - k + i) // i. After step
When the problem says "return the answer modulo
MOD = 10**9 + 7
def build(n):
fact = [1] * (n + 1)
for i in range(1, n + 1):
fact[i] = fact[i - 1] * i % MOD
inv = [1] * (n + 1)
inv[n] = pow(fact[n], MOD - 2, MOD) # Fermat inverse
for i in range(n, 0, -1):
inv[i - 1] = inv[i] * i % MOD
return fact, inv
def ncr(n, r, fact, inv):
if r < 0 or r > n:
return 0
return fact[n] * inv[r] % MOD * inv[n - r] % MODPascal's triangle costs fact[n] // (fact[r] * fact[n - r]) % MOD after the factorials were already reduced, which gives a wrong answer because integer division does not survive reduction modulo
Permutations are what happens when you stop treating a chosen set as a bag of items and start treating it like a sequence. In algorithm terms, you’ve moved from “which items?” to “in what order?”
First step: Decide whether you need every ordering, only the next one, or only the
$k$ -th one, and whether the input has repeated values. Listing all$n!$ orderings is only realistic for$n$ up to about 8 to 10, so "next" and "$k$-th" questions should be answered by construction.
There are two closely related ideas:
All orderings of the entire set A (size
Count:
n!
Example A={a,b,c}:
abc acb bac bca cab cba
Ordered sequences of length
Count:
P(n,k) = n·(n-1)·...·(n-k+1) = n!/(n-k)!
Proper math:
A do/don’t that prevents classic mistakes: do decide early whether repetition is allowed; don’t mix “without repetition” formulas (like $P(n,k)$) with “with repetition” reasoning (like
For
start
├─ pick a ─┬─ then b => (a,b)
│ └─ then c => (a,c)
├─ pick b ─┬─ then a => (b,a)
│ └─ then c => (b,c)
└─ pick c ─┬─ then a => (c,a)
└─ then b => (c,b)
This tree is the “nested loops in your head” picture: each level is a choice, and the number of leaves is the total count.
A
P(n,k) = C(n,k) · k!
Proper math:
Because:
- choose the
$k$ elements (order-free):$\binom{n}{k}$ - order them:
$k!$
To enumerate all permutations of
- Time:
$\Theta(n \cdot n!)$ ($n$ work per permutation) - Space:
$\Theta(n)$ recursion or in-place swaps
Classic algorithms:
- Heap’s algorithm (efficient swaps)
- next_permutation (lexicographic)
- backtracking swap recursion
In-place swapping limits working memory, but explicitly producing every permutation still takes factorially many outputs. Estimate the output size before choosing enumeration, and use streaming when results can be processed one at a time.
LeetCode 46 Permutations uses the standard backtracking with a used array, described in the backtracking note. LeetCode 47 Permutations II adds repeated values, and the number of distinct results drops to
To generate each distinct ordering once, sort the input and, at each depth, skip a value that equals its left neighbour when that neighbour is not currently used. This forces equal values to be placed in their original left-to-right order, so swapping two equal copies never creates a second copy of the same result. LeetCode 996 Number of Squareful Arrays uses the same skip rule.
def permute_unique(nums):
nums.sort()
used, path, out = [False] * len(nums), [], []
def go():
if len(path) == len(nums):
out.append(path[:])
return
for i in range(len(nums)):
if used[i] or (i > 0 and nums[i] == nums[i - 1] and not used[i - 1]):
continue
used[i] = True
path.append(nums[i])
go()
path.pop()
used[i] = False
go()
return outTime is
LeetCode 31 Next Permutation asks for the next arrangement in lexicographic order, in place. Scanning from the right, the longest non-increasing suffix is already the largest possible ordering of its items, so nothing inside it can grow. The change must happen just before it.
The algorithm has three steps. First, find the pivot: the largest index
For 1 3 5 4 2, the pivot is 3, the rightmost larger value in the suffix is 4, swapping gives 1 4 5 3 2, and reversing the suffix gives 1 4 2 3 5.
def next_permutation(a):
i = len(a) - 2
while i >= 0 and a[i] >= a[i + 1]:
i -= 1
if i >= 0:
j = len(a) - 1
while a[j] <= a[i]:
j -= 1
a[i], a[j] = a[j], a[i]
a[i + 1:] = reversed(a[i + 1:])It runs in > and <) in the two scans, which picks the wrong pivot or swap target when values repeat.
LeetCode 60 Permutation Sequence asks for the
So with a 0-based rank 2, then 3, then 1, then 4, giving 2314.
from math import factorial
def kth_permutation(n, k):
items = list(range(1, n + 1))
k -= 1 # switch to a 0-based rank
out = []
for size in range(n, 0, -1):
idx, k = divmod(k, factorial(size - 1))
out.append(items.pop(idx))
return "".join(map(str, out))This is
Subsets and permutations without repetition use each element at most once. Cartesian products and powers allow the same value in different positions. If reuse is allowed, the counting flips in a really clean way: “no repetition” tends to create factorials and falling factorials; “repetition allowed” tends to create powers and stars-and-bars.
First step: Ask whether the things being placed are identical or distinguishable, and whether the slots or bins are ordered. Distinct choices in ordered positions with reuse give a plain power, while identical items dropped into distinct bins give stars and bars.
If you choose
A^k = A × A × ... × A (k times)
|A^k| = n^k
Proper Math:
This is exactly “all
Number of size-$k$ multisets from
C(n+k-1, k)
For
If you have
n^k
This use of “permutations with repetition” means unrestricted sequences. Arranging a fixed multiset is a different problem: if aab has three orderings: aab, aba, and baa.
A useful variant of stars and bars requires every bin to get at least one item. Put one item in each of the
First step: If a problem counts nested or recursive structures (balanced brackets, tree shapes, ways to split a sequence around a root), compute the first few answers by hand. If you see 1, 1, 2, 5, 14, 42, you are looking at Catalan numbers.
The Catalan numbers count structures that split into a left part and a right part around one chosen piece. They start at
with the closed form
LeetCode 96 Unique Binary Search Trees is the recurrence directly: pick root
def num_trees(n):
dp = [1] + [0] * n
for nodes in range(1, n + 1):
for root in range(1, nodes + 1):
dp[nodes] += dp[root - 1] * dp[nodes - root]
return dp[n]The recurrence costs ) only while the number of closes is below the number of opens.
This section is the “snap everything into place” moment. If you ever feel lost, switching to the function viewpoint usually makes the counting obvious: how many ways can I assign labels to inputs?
A subset
f: A → {0,1}
f(x)=1 if x∈S else 0
Number of such functions is
A length-$k$ sequence is:
g: {1..k} → A
Number is
A permutation is a bijection:
p: {1..n} → A
Number is
So:
- power set = all
${0,1}$ -labelings of$A$ - Cartesian powers = all
$k$ -position labelings by$A$ - permutations = all one-to-one labelings of positions by
$A$
A do/don’t here: do use “functions” when you’re stuck; don’t overcomplicate it with new symbols, this is meant to be the simplest mental model.
If you generate these objects, the minimum time is at least the number of outputs. The bounds below assume nonempty outputs are copied explicitly and each element takes constant time to copy. For
So:
| Structure | Count | Typical enumeration time |
|---|---|---|
|
|
||
| permutations | ||
|
|
||
|
|
This is why many problems that ask you to “try all subsets” are exponential: the search space literally has
One last do/don’t that matters in real projects: do treat these counts like early warning signs (a design review for your algorithm), and don’t wait until you’ve implemented everything to realize you built an
First step: Look for the words "at least one", "or", or "divisible by any of". Decide whether it is easier to count the union directly with inclusion-exclusion or to count the complement ("none of them") and subtract from the total.
Adding the sizes of overlapping sets counts the overlaps more than once. Inclusion-exclusion corrects this by alternately subtracting and adding the intersections:
A small example: among
LeetCode 1201 Ugly Number III combines this with binary search. Count the numbers up to
from math import lcm
def nth_ugly_number(n, a, b, c):
ab, ac, bc, abc = lcm(a, b), lcm(a, c), lcm(b, c), lcm(a, b, c)
def count(x):
return (x // a + x // b + x // c
- x // ab - x // ac - x // bc + x // abc)
lo, hi = 1, 2 * 10**9
while lo < hi:
mid = (lo + hi) // 2
if count(mid) >= n:
hi = mid
else:
lo = mid + 1
return loWith
First step: Check whether the universe is small (at most 32 or 64 distinct items) or whether the problem is about values that "appear twice" or "appear once". Small universes fit in an integer used as a set, and pairing problems usually collapse under XOR.
An integer whose bit a | b is the union, a & b the intersection, a & ~b the difference, and a ^ b the symmetric difference. Add item a | (1 << i), remove it with a & ~(1 << i), and complement within a ^ ((1 << n) - 1).
Two expressions show up constantly. x & (x - 1) removes the lowest set bit, and x & -x isolates it. LeetCode 231 Power of Two is n > 0 and n & (n - 1) == 0. LeetCode 191 Number of 1 Bits repeats n &= n - 1 and counts the steps, so it runs once per set bit. LeetCode 338 Counting Bits fills a table with bits[i] = bits[i >> 1] + (i & 1), because shifting right drops only the last bit.
XOR acts like toggling membership:
LeetCode 260 Single Number III has two unique values
def single_number_iii(nums):
x = 0
for v in nums:
x ^= v
low = x & -x # a bit where the two answers differ
a = 0
for v in nums:
if v & low:
a ^= v
return [a, x ^ a]All of these run in n & n - 1 == 0 parses as n & ((n - 1) == 0) (Java rejects it outright), so always write (n & (n - 1)) == 0.
First step: Decide whether duplicates matter. A plain set answers "is it present", while a counter (multiset) answers "how many times", and problems like intersection come in both flavours.
When the universe is large, a hash set gives len(set(nums)) < len(nums). LeetCode 349 Intersection of Two Arrays is a set intersection, while LeetCode 350 Intersection of Two Arrays II keeps multiplicities, which in Python is (Counter(a) & Counter(b)).elements() and takes the minimum count of each value.
LeetCode 128 Longest Consecutive Sequence needs
def longest_consecutive(nums):
s = set(nums)
best = 0
for x in s:
if x - 1 not in s: # x starts a run
y = x
while y + 1 in s:
y += 1
best = max(best, y - x + 1)
return bestLeetCode 41 First Missing Positive asks for the same idea in a[i], a[a[i] - 1] = a[a[i] - 1], a[i] in Python assigns a[i] first and then reads the wrong slot.
Set relationships also drive counting problems such as LeetCode 2306 Naming a Company. Group the suffixes by first letter; for two letters with suffix sets
Hash-set operations run in nums instead of the set, which repeats the inner walk for duplicated run starts and can degrade toward quadratic time.
Ask two questions:
- No → combinations / subsets / multisets
- Yes → permutations / sequences / tuples
- No repetition → factorial / falling factorial
- Repetition allowed → powers / stars-and-bars
Decision table:
No repetition Repetition allowed
Order matters P(n,k)=n!/(n-k)! n^k
Order doesn't matter C(n,k)=n!/(k!(n-k)!) C(n+k-1,k)
Use the table by deciding first whether order matters and then whether elements can be reused. Those two assumptions distinguish the four counting problems.
Many interview counting problems reduce to one of a short list of formulas. Identify the structure first, then look up the count.
| Situation | Count | Example problem |
|---|---|---|
| Sequences of length |
PIN codes of length |
|
| All subsets of |
78 Subsets | |
| Orderings of |
46 Permutations | |
| Ordered picks of |
arranging |
|
| Unordered picks of |
77 Combinations | |
| Multisets of size |
|
|
|
|
splitting |
|
| Orderings of a multiset with counts |
47 Permutations II | |
| Right and down paths in an |
62 Unique Paths | |
| Balanced strings of |
22 Generate Parentheses, 96 Unique BSTs | |
| (mask, submask) pairs over |
DP over subsets | |
| Nonempty subsets of |
1201 Ugly Number III |
- Power set / combinations show up in: subset-sum, knapsack variants, feature selection, graph vertex subsets, brute-force optimization.
- Permutations show up in: traveling salesman, scheduling, ordering constraints, anagrams, backtracking search.
- Cartesian products show up in: nested loops, join operations in databases, grid/coordinate enumeration, state spaces.
A yes/no branch for each of
A tiny “big picture” diagram: how they build on each other
Sets (A)
|
+--> Cartesian product (A×B) ---> tuples / coordinates
| |
| +--> Cartesian power (A^k) ---> sequences, strings (n^k)
|
+--> Power set P(A) ---> all subsets (2^n)
|
+--> k-subsets ---> combinations C(n,k)
|
+--> order them ---> k-permutations = C(n,k)·k! = P(n,k)
Most problems in this area announce their structure in a few stock phrases. Matching those phrases to a technique before writing any code saves you from building the wrong search.
| If the problem says | What it means for your code |
|---|---|
| "order does not matter", "choose", "groups", "teams" | Combinations: generate with a start index, count with |
| "arrangements", "orderings", "order matters" | Permutations: track used items, count with |
| "all possible subsets" or "the power set" | Loop masks from |
| "each element may be used unlimited times" | Recurse with the same index, not the next one; counts become powers or stars and bars |
| "may contain duplicates" and "no duplicate answers" | Sort and skip equal neighbours at the same depth; counts divide by repeated factorials |
| "return the answer modulo |
Reduce after every addition and multiplication, and replace division with a modular inverse |
|
|
|
|
|
Submask enumeration at |
|
|
Listing all permutations is feasible |
|
|
Use a formula with precomputed factorials, never enumeration |
| "the |
Build it directly with the factorial number system |
| "the next greater arrangement" or "next lexicographic order" | Next permutation: find pivot, swap with rightmost larger, reverse suffix |
| "every element appears twice except one" | XOR everything so the pairs cancel |
| "every element appears three times except one" | Count each bit position modulo 3 |
| "adjacent values differ by exactly one bit" | Gray code, i ^ (i >> 1)
|
| "divisible by a, b or c" or "at least one of" | Inclusion-exclusion with lcm, or count the complement |
| "valid parentheses" or "structurally unique BSTs" | Catalan numbers, by recurrence or closed form |
| "O(n) time" on unsorted values, or "O(1) extra space" with values in 1 to n | Hash set, or use the array itself as the set by index |