# Famous Algorithms & Proofs: Max-Flow Min-Cut, Huffman Trees, Kadane, Edit Distance & Cycle Detection
Exam: GATE Computer Science & Information Technology (GATE CS)
Subject: Algorithms
Canonical URL: https://gateandnet.com/exams/gate-cs/algorithms/max-flow-huffman-kadane-edit-distance-and-floyd-cycle

> Ford-Fulkerson residual networks & Edmonds-Karp O(VE^2) bound, Max-Flow Min-Cut theorem, Huffman optimal prefix code tree properties, Kadane O(n) subarray, Levenshtein DP, and Floyd cycle pointer math.

## 1. Network Flow: Residual Graphs, Augmenting Paths & Min-Cut

- **Ford-Fulkerson Method:** Repeatedly finds an $s \leadsto t$ path in the **Residual Graph $G_f$** (including backward edges $c_f(v, u) = f(u, v)$ that allow *"undoing"* earlier greedy flow!). On integer capacities, runtime $\mathcal{O}(E \cdot |f^*|)$ can be pseudo-polynomial; choosing **shortest augmenting paths via BFS** (**Edmonds-Karp**) guarantees strongly polynomial **$\mathcal{O}(V \cdot E^2)$**!

## 2. Three Must-Know Linear & DP Algorithmic Gems

1. **Kadane’s Maximum Contiguous Subarray ($\Theta(n)$ time, $\mathcal{O}(1)$ space):**
   $$\text{cur}_i = \max(A[i], \; \text{cur}_{i-1} + A[i]), \qquad \text{best} = \max_i \text{cur}_i$$
2. **Edit (Levenshtein) Distance `dp[i][j]` ($\Theta(mn)$):** Minimum insertions, deletions, and substitutions to convert $X[1..m]$ into $Y[1..n]$:
   $$dp[i][j] = \begin{cases} dp[i-1][j-1] & X[i] = Y[j] \\ 1 + \min\big(dp[i-1][j],\; dp[i][j-1],\; dp[i-1][j-1]\big) & X[i] \neq Y[j] \end{cases}$$
3. **Floyd’s Tortoise & Hare Cycle Detection + Boyer-Moore Majority Vote ($\Theta(n)$ time, $\mathcal{O}(1)$ space):**
   - **Floyd’s Cycle:** Slow moves $1$ step, Fast moves $2$ steps. Once they meet inside a cycle of length $L$, resetting one pointer to `head` and advancing both $1$ step at a time meets at the **exact cycle entry node**!
   - **Boyer-Moore Majority ($> \lfloor n/2 \rfloor$ occurrences):** Pairwise cancel distinct elements using `(candidate, count)` in $1$ pass + $1$ verification pass!

## Solved Practice Questions & PYQs

### [GATE CS 2021 | NAT]
Five characters `a, b, c, d, e` occur with frequencies `10, 15, 12, 3, 4` respectively in a file. What is the **total number of bits** needed to encode the file using an optimal **Huffman prefix code**?
**Correct Answer:** 95
**Solution:** Repeatedly merge the two lowest frequencies (sum of internal node weights = total bit length):
1. `3 + 4 = 7` $\to \{7, 10, 12, 15\}$
2. `7 + 10 = 17` $\to \{12, 15, 17\}$
3. `12 + 15 = 27` $\to \{17, 27\}$
4. `17 + 27 = 44`
Total encoded bits $= 7 + 17 + 27 + 44 = \mathbf{95}$ (leaf check: $3(3)+4(3)+10(2)+12(2)+15(2) = 9+12+20+24+30 = 95$).

### [GATE CS 2023 | NAT]
Using **Kadane’s Algorithm**, what is the maximum contiguous subarray sum of the array `[-2, 1, -3, 4, -1, 2, 1, -5, 4]`?
**Correct Answer:** 6
**Solution:** Contiguous subarray **`[4, -1, 2, 1]`** achieves the maximum sum $4 - 1 + 2 + 1 = \mathbf{6}$.
