Minimum Spanning Tree Prim's Algorithm in DSA C# - Time & Space Complexity
We want to understand how the time needed to find a minimum spanning tree using Prim's algorithm grows as the graph gets bigger.
Specifically, how does the number of steps change when the graph has more points and connections?
Analyze the time complexity of the following code snippet.
// Prim's algorithm to find MST
int vertices = graph.Length;
bool[] inMST = new bool[vertices];
int[] key = new int[vertices];
for (int i = 0; i < vertices; i++) key[i] = int.MaxValue;
key[0] = 0;
for (int count = 0; count < vertices - 1; count++) {
int u = MinKey(key, inMST);
inMST[u] = true;
for (int v = 0; v < vertices; v++) {
if (graph[u][v] != 0 && !inMST[v] && graph[u][v] < key[v]) {
key[v] = graph[u][v];
}
}
}
This code finds the minimum spanning tree of a graph using Prim's algorithm with a simple array to pick the next vertex.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The outer loop runs once for each vertex, and inside it, the inner loop checks all vertices to update keys.
- How many times: The outer loop runs n times, and the inner loop runs n times for each outer loop, making the key updates happen about n x n = n² times.
As the number of vertices grows, the steps needed grow roughly with the square of the number of vertices.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 100 key updates |
| 100 | About 10,000 key updates |
| 1000 | About 1,000,000 key updates |
Pattern observation: Doubling the number of vertices roughly quadruples the work because of the nested loops.
Time Complexity: O(n²)
This means the time to find the minimum spanning tree grows roughly with the square of the number of vertices in the graph.
[X] Wrong: "Prim's algorithm always runs in linear time because it just picks the smallest edge each time."
[OK] Correct: Picking the smallest edge requires checking many edges, and with this simple approach, it takes more time as the graph grows, not just a fixed amount.
Understanding how Prim's algorithm scales helps you explain your choices clearly and shows you know how to handle graphs efficiently in real problems.
"What if we used a priority queue (min-heap) to pick the next vertex instead of scanning all vertices? How would the time complexity change?"
Practice
Solution
Step 1: Understand Prim's Algorithm purpose
Prim's Algorithm is designed to find a tree that connects all vertices with the smallest total edge weight.Step 2: Compare with other graph tasks
Shortest path, cycle detection, and sorting vertices are different problems solved by other algorithms.Final Answer:
To find the minimum spanning tree of a connected weighted graph -> Option AQuick Check:
Prim's Algorithm = Minimum Spanning Tree [OK]
- Confusing Prim's with shortest path algorithms
- Thinking it detects cycles
- Assuming it sorts graph nodes
Solution
Step 1: Identify correct data structure for Prim's
Prim's Algorithm requires a priority queue to pick the minimum weight edge efficiently.Step 2: Match with C# syntax
PriorityQueue<TElement, TPriority> is the correct .NET 6+ class for priority queues.Final Answer:
var pq = new PriorityQueue<int, int>(); -> Option DQuick Check:
PriorityQueue<int,int> = Correct initialization [OK]
- Using Queue instead of PriorityQueue
- Using Stack which is LIFO, not priority-based
- Using SortedList which is not a priority queue
int[,] graph = {
{0, 2, 0, 6},
{2, 0, 3, 8},
{0, 3, 0, 0},
{6, 8, 0, 0}
};
var mst = PrimMST(graph);
Console.WriteLine(string.Join(", ", mst));
// PrimMST returns the parent array representing MST
What is the output printed by this code?Solution
Step 1: Run Prim's Algorithm on given graph
Start from node 0: parent[0] = -1. Choose edges with minimum weights connecting new nodes: 0-1 (2), 1-2 (3), 0-3 (6).Step 2: Construct parent array
Node 0 has no parent (-1). Node 1's parent is 0. Node 2's parent is 1. Node 3's parent is 0.Final Answer:
[ -1, 0, 1, 0 ] -> Option AQuick Check:
Parent array = [-1,0,1,0] [OK]
- Mixing up parent indices
- Starting from wrong node
- Ignoring zero weights as no edge
int V = 5;
int[] key = new int[V];
bool[] mstSet = new bool[V];
for (int i = 0; i < V; i++) {
key[i] = int.MaxValue;
mstSet[i] = false;
}
key[0] = 0;
int parent[] = new int[V];
for (int count = 0; count < V - 1; count++) {
int u = MinKey(key, mstSet);
mstSet[u] = true;
for (int v = 0; v < V; v++) {
if (graph[u, v] != 0 && mstSet[v] == false && graph[u, v] < key[v]) {
parent[v] = u;
key[v] = graph[u, v];
}
}
}
What is the bug?Solution
Step 1: Check parent array initialization
The parent array is declared but not initialized with any default values, so it contains garbage values initially.Step 2: Importance of initializing parent array
Without initialization, parent[v] may hold invalid data before assignment, causing incorrect MST representation.Final Answer:
The parent array is not initialized before use -> Option CQuick Check:
Parent array must be initialized [OK]
- Ignoring uninitialized parent array
- Thinking key or mstSet are incorrect
- Changing loop bounds unnecessarily
(0-1: 4), (0-2: 3), (1-2: 1), (1-3: 2), (2-3: 4), (3-4: 2), (4-5: 6)Using Prim's Algorithm starting from node 0, which edges will be included in the minimum spanning tree?
Solution
Step 1: Start from node 0 and pick minimum edges stepwise
From 0, edges are (0-1:4) and (0-2:3). Pick (0-2) with weight 3.Step 2: Add next minimum edges connecting new nodes
From nodes {0,2}, edges are (1-2:1), (0-1:4), (2-3:4). Pick (1-2) with weight 1.Step 3: Continue adding minimum edges
From {0,1,2}, edges are (1-3:2), (2-3:4), (0-1:4). Pick (1-3) with weight 2.Step 4: Add edges to connect remaining nodes
From {0,1,2,3}, edges are (3-4:2), (4-5:6). Pick (3-4) with weight 2, then (4-5) with weight 6.Final Answer:
(0-2), (1-2), (1-3), (3-4), (4-5) -> Option BQuick Check:
Edges chosen minimize total weight [OK]
- Picking edges with higher weights first
- Not updating the set of connected nodes
- Including edges that form cycles
Ready to prove it?
Pass the test and this pattern moves unknown
