Courses / DSA Patterns for Working Engineers / Chapter 11
Module 4 · Binary search, subsets, greedy, backtracking and DP · Chapter 11 of 39
Subsets: Every Subset, Permutation and Combination
Builds on The Coding Interview: How the Round Runs and How to Prepare. Next up: Greedy Techniques: Safe Local Choices and How to Prove Them.
Part 1 · Introduction to subsets
Subsets, orders and combinations
Choosing a team, a bundle of add-ons or a seating order are all questions of listing every possibility. The number of possibilities grows so fast that knowing the count first decides whether listing is an option at all.
A subset of n items is any selection of them, including none and all. Order does not matter: choosing the soap then the tea is the same subset as choosing the tea then the soap. A permutation is an ordering of all n items, where order does matter. A combination of size r is a subset with exactly r items.
Counting comes first, because it tells you how long the listing will take. Each item is either in or out, two choices each, so n items have 2^n subsets. For orders, any of n items can go first, any of the remaining n - 1 second, and so on, so there are n factorial of them: n times n - 1 times n - 2, down to 1. Combinations of size r number n factorial divided by the product of r factorial and n - r factorial.
| Items n | Subsets 2^n | Orders (n factorial) |
|---|---|---|
| 3 | 8 | 6 |