# Shortest Path & MST Algorithms: Dijkstra, Bellman-Ford, Prim & Kruskal
Exam: GATE Computer Science & Information Technology (GATE CS)
Subject: Algorithms
Canonical URL: https://gateandnet.com/exams/gate-cs/algorithms/shortest-path-and-mst-algorithms

> Edge relaxation, negative edge traps, Disjoint-Set Union Kruskal complexity, and MST uniqueness theorem.

## Shortest Path & MST Master Comparison

| Algorithm | Problem | Negative Weights Allowed? | Time Complexity |
| :--- | :--- | :--- | :--- |
| **BFS** | Unweighted Shortest Path | N/A | $\mathcal{O}(V + E)$ |
| **DAG Relaxation** | Single-Source on DAG | **Yes** | $\mathcal{O}(V + E)$ |
| **Dijkstra** | Single-Source Shortest Path | **No** | $\mathcal{O}((V+E)\log V)$ |
| **Bellman-Ford** | Single-Source + Neg Cycle Check | **Yes** | $\mathcal{O}(V \cdot E)$ |
| **Floyd-Warshall** | All-Pairs Shortest Path | **Yes** | $\mathcal{O}(V^3)$ |
| **Kruskal / Prim** | Minimum Spanning Tree | **Yes!** (MST works on negative edges) | $\mathcal{O}(E \log V)$ |

> [!IMPORTANT]
> **MST Uniqueness Theorem:**
> - If all edge weights in $G$ are **distinct**, the Minimum Spanning Tree is **guaranteed to be unique**!
> - Conversely, a unique MST does *not* require all edge weights to be distinct (e.g., a tree with equal weights has a unique MST).


## Solved Practice Questions & PYQs

### [GATE CS Algorithms | MCQ]
What is the worst-case time complexity of **Dijkstra’s single-source shortest path algorithm** on a graph $G = (V, E)$ implemented using a **Binary Min-Heap** adjacency list?
**Correct Answer:** B
**Solution:** With a Binary Min-Heap, `Extract-Min` runs $V$ times ($\mathcal{O}(V \log V)$) and `Decrease-Key` runs at most $E$ times ($\mathcal{O}(E \log V)$), giving $\mathcal{O}((V + E)\log V)$.

### [GATE CS Algorithms | MCQ]
Five characters have frequencies $5, 9, 12, 13, 16$. Using **Huffman optimal prefix coding**, what is the total weighted number of bits required to encode all $55$ characters?
**Correct Answer:** B
**Solution:** Huffman merges smallest pairs repeatedly: $(5+9=14)$, next $(12+13=25)$, next $(14+16=30)$, finally $(25+30=55)$. Sum of internal node weights $= 14 + 25 + 30 + 55 = \mathbf{124}$ bits!
