# Combinatorics, Pigeonhole Principle, Inclusion-Exclusion & Generating Functions
Exam: GATE Computer Science & Information Technology (GATE CS)
Subject: Engineering Mathematics & Discrete Math
Canonical URL: https://gateandnet.com/exams/gate-cs/engineering-mathematics/combinatorics-pigeonhole-generating-functions

> Stars-and-bars integer solutions, Generalized Pigeonhole Principle, Derangements, Catalan numbers, and Ordinary Generating Functions for linear recurrences.

## 1. Counting Mappings Between Finite Sets

Let $|A| = m$ and $|B| = n$. Counting functions $f: A \to B$ is a guaranteed 1- or 2-mark question in GATE CS and UGC NET:

| Function Class | Condition | Exact Count Formula |
| :--- | :--- | :--- |
| **Total Functions** | Unrestricted | $n^m$ |
| **Injective (One-to-One)** | $m \le n$ | $P(n, m) = \frac{n!}{(n-m)!}$ (0 if $m > n$) |
| **Surjective (Onto)** | $m \ge n$ | $\sum_{k=0}^{n} (-1)^k \binom{n}{k}(n-k)^m = n! \, S(m, n)$ |
| **Bijective** | $m = n$ | $n!$ |

> [!FORMULA]
> **Generalized Pigeonhole Principle:** If $N$ objects are placed into $k$ boxes, then at least one box contains at least $\lceil N / k \rceil$ objects. Conversely, to guarantee at least $r$ objects of the same type among $k$ types, pick $k(r - 1) + 1$ objects.

## 2. Stars and Bars & Derangements

The number of non-negative integer solutions to $x_1 + x_2 + \dots + x_r = n$ ($x_i \ge 0$) is:

$$
\binom{n + r - 1}{r - 1}
$$

If every variable must be strictly positive ($x_i \ge 1$), substitute $y_i = x_i - 1 \ge 0$ to obtain $\binom{n - 1}{r - 1}$.

**Derangements ($D_n$):** Permutations of $n$ elements where **no element stays in its original position** ($\pi(i) \neq i$ for all $i$):

$$
D_n = (n-1)(D_{n-1} + D_{n-2}), \quad D_1 = 0,\; D_2 = 1,\; D_3 = 2,\; D_4 = 9,\; D_5 = 44
$$

## 3. Catalan Numbers & Ordinary Generating Functions

The sequence $C_n = \frac{1}{n+1}\binom{2n}{n}$ ($1, 1, 2, 5, 14, 42, 132, \dots$) simultaneously counts:
- Number of structurally distinct **Binary Search Trees (BSTs)** with $n$ keys
- Number of **valid balanced parenthesizations** of $n$ pairs
- Number of ways to parenthesize a product of $n+1$ matrices (Matrix Chain Multiplication)
- Number of **stack-sortable permutations** of $\{1, 2, \dots, n\}$

> [!TRAP]
> **Labeled vs Unlabeled Binary Trees:** Unlabeled binary trees with $n$ nodes = $C_n$. **Labeled** binary trees with $n$ distinct nodes = $n! \cdot C_n$ (whereas BSTs with $n$ distinct keys = $C_n$ because the inorder traversal is fixed!).

## Solved Practice Questions & PYQs

### [GATE CS Discrete Math | MCQ]
How many structurally distinct **Binary Search Trees (BSTs)** can be formed using $5$ distinct keys $\{10, 20, 30, 40, 50\}$?
**Correct Answer:** B
**Solution:** The number of distinct BSTs on $n$ distinct keys is the $n$-th **Catalan number** $C_n = \frac{1}{n+1}\binom{2n}{n}$. For $n = 5$: $C_5 = \frac{1}{6}\binom{10}{5} = \frac{252}{6} = \mathbf{42}$.
