itertools: combinations, permutations, product

These three generate every arrangement, lazily:

  • combinations(xs, r): every choice of r items, order ignored. C(n, r) of them. Pairs are n * (n - 1) / 2, which is O(n^2).
  • permutations(xs, r): every ordering of r items. n! of them when r is n. Ten items is already 3,628,800.
  • product(a, b): every pair from a and b, like nested loops. product(xs, repeat=3) is len(xs) ** 3 tuples.

They are great for brute force and for checking a faster solution on small inputs. But they make the cost easy to hide. A one-liner over combinations(nums, 2) is still O(n^2), and an interviewer will ask you to name that cost and then beat it, often with a set or a dict. The Performance challenges are full of these.

math.comb(n, r), math.perm(n, r), and math.factorial(n) give the counts without generating anything.

Run it, then raise n and watch how fast the counts grow.