Lesson 9 of 15

Advanced Combinatorics

Stars and Bars, Stirling Numbers, Catalan Numbers

Stars and Bars

The number of ways to distribute nn identical objects into kk distinct bins (allowing empty bins) is: (n+k1k1)\binom{n+k-1}{k-1}

Intuition: arrange nn stars and k1k-1 bars in a row — each arrangement defines a distribution.

Example: 3 coins into 2 pockets: (41)=4\binom{4}{1} = 4 ways (0+3, 1+2, 2+1, 3+0... but 4 because 0 included).

Wait: 5 balls into 3 bins: (5+3131)=(72)=21\binom{5+3-1}{3-1} = \binom{7}{2} = 21.

Stirling Numbers of the Second Kind

S(n,k)S(n, k) counts the ways to partition nn labeled elements into kk non-empty unlabeled subsets: S(n,k)=kS(n1,k)+S(n1,k1),S(0,0)=1S(n,k) = k \cdot S(n-1,k) + S(n-1,k-1), \quad S(0,0)=1

Catalan Numbers

Cn=1n+1(2nn)C_n = \frac{1}{n+1}\binom{2n}{n}

They count: valid parenthesizations, full binary trees, monotone lattice paths, and more. C0=1,C1=1,C2=2,C3=5,C4=14,C5=42C_0=1, C_1=1, C_2=2, C_3=5, C_4=14, C_5=42.

import math

def stars_and_bars(n, k):
    return math.comb(n + k - 1, k - 1)

def catalan(n):
    return math.comb(2 * n, n) // (n + 1)

print(stars_and_bars(5, 3))  # 21
print(catalan(5))            # 42

Your Task

Implement stars_and_bars(n, k), stirling_second(n, k), and catalan(n).

Pyodide loading...
Loading...
Click "Run" to execute your code.