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 changes as the graph grows.
How does the algorithm's work increase when the number of nodes and edges increases?
Analyze the time complexity of the following Prim's algorithm code snippet.
void primMST(int graph[V][V]) {
int key[V];
bool mstSet[V];
for (int i = 0; i < V; i++) {
key[i] = INT_MAX;
mstSet[i] = false;
}
key[0] = 0;
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] && !mstSet[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 an adjacency matrix.
Look at the loops and repeated steps:
- Primary operation: The outer loop runs once for each vertex (V times).
- Inner loop: For each vertex chosen, it checks all vertices to update keys (V times).
- Dominant operation: The nested loops together cause about V x V = V² checks.
As the number of vertices (n) grows, the work grows roughly with the square of n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 100 checks |
| 100 | About 10,000 checks |
| 1000 | About 1,000,000 checks |
Pattern observation: Doubling the number of vertices roughly quadruples the work.
Time Complexity: O(V^2)
This means the time needed grows roughly with the square of the number of vertices in the graph.
[X] Wrong: "Prim's algorithm always runs in linear time O(V)."
[OK] Correct: Because it checks all vertices repeatedly, the time grows with V squared, not just V.
Understanding how Prim's algorithm scales helps you explain your choices and shows you know how algorithms behave with bigger data.
"What if we used a priority queue (min-heap) instead of scanning all vertices to find the minimum key? 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 minimum total edge weight.Step 2: Differentiate from other graph algorithms
It is not used for shortest path, cycle detection, or sorting vertices, which are different problems.Final Answer:
To find the minimum spanning tree of a connected weighted graph -> Option CQuick Check:
Prim's Algorithm = Minimum Spanning Tree [OK]
- Confusing Prim's with shortest path algorithms
- Thinking it detects cycles
- Assuming it sorts nodes
Solution
Step 1: Understand key array role
The key array stores minimum edge weights to include each vertex; initially, all are set to a very large value (infinity).Step 2: Check initialization options
Setting key[i] = INT_MAX correctly represents infinity; other options set to 0 or -1 are incorrect for this purpose.Final Answer:
int key[V]; for(int i=0; i -> Option AQuick Check:
Initialize keys with INT_MAX for minimum edge tracking [OK]
- Initializing keys with 0 instead of INT_MAX
- Using negative values incorrectly
- Not initializing keys at all
0 - 1 : 10 0 - 2 : 6 0 - 3 : 5 1 - 3 : 15 2 - 3 : 4What is the total weight of the minimum spanning tree found by Prim's Algorithm starting from vertex 0?
Solution
Step 1: Start from vertex 0 and pick minimum edges
Edges from 0: (0-3)=5, (0-2)=6, (0-1)=10. Pick (0-3)=5 first.Step 2: Add next minimum edge connecting new vertices
From vertices {0,3}, edges are (3-2)=4, (3-1)=15, (0-2)=6, (0-1)=10. Pick (3-2)=4 next.Step 3: Add last vertex with minimum edge
From {0,3,2}, edges to 1 are (0-1)=10 and (3-1)=15. Pick (0-1)=10.Step 4: Calculate total weight
Total = 5 + 4 + 10 = 19.Final Answer:
19 -> Option BQuick Check:
Sum of chosen edges = 19 [OK]
- Choosing edges with larger weights first
- Not updating the set of included vertices
- Adding edges that form cycles
const int V = 4;
int key[V] = {INT_MAX, INT_MAX, INT_MAX, INT_MAX};
bool mstSet[V] = {false, false, false, false};
key[0] = 0;
for (int count = 0; count < V - 1; count++) {
int u = -1;
for (int v = 0; v < V; v++) {
if (!mstSet[v] && (u == -1 || key[v] < key[u]))
u = v;
}
mstSet[u] = true;
for (int v = 0; v < V; v++) {
if (graph[u][v] && !mstSet[v] && graph[u][v] < key[v])
key[v] = graph[u][v];
}
}
Solution
Step 1: Analyze the neighbor update condition
The condition if(graph[u][v] && !mstSet[v] && graph[u][v] < key[v]) uses graph[u][v] as a boolean check (true if non-zero).Step 2: Identify the bug
This implicit check assumes positive weights and treats 0 as no edge. Standard implementations explicitly use graph[u][v] != 0 to clearly indicate checking for edge existence (non-zero weight).Step 3: Rule out other options
A: 'u' is correctly initialized to -1 inside each iteration. B: V-1 iterations build the tree correctly. C: key array is initialized with INT_MAX.Final Answer:
The condition 'graph[u][v]' should check for non-zero edges -> Option AQuick Check:
Edge check: graph[u][v] != 0 [OK]
- Misinitializing 'u' outside the loop
- Incorrect loop range
- Not initializing key array properly
0-1: 3, 0-3: 1, 1-2: 1, 1-3: 3, 1-4: 10, 2-4: 5, 3-4: 6, 4-5: 2If Prim's Algorithm starts from vertex 0, which edge will NOT be included in the minimum spanning tree?
Solution
Step 1: Build MST step-by-step from vertex 0
Start at 0: edges (0-3)=1, (0-1)=3. Pick (0-3)=1 first.Step 2: Add next minimum edges connecting new vertices
From {0,3}, edges: (3-1)=3, (3-4)=6, (0-1)=3. Pick (0-1)=3 or (3-1)=3 (same weight). Pick (0-1)=3.Step 3: Continue adding minimum edges
From {0,1,3}, edges: (1-2)=1, (1-4)=10, (3-4)=6. Pick (1-2)=1.Step 4: Add edge to vertex 4
From {0,1,2,3}, edges: (2-4)=5, (3-4)=6, (1-4)=10. Pick (2-4)=5.Step 5: Add edge to vertex 5
From {0,1,2,3,4}, edge: (4-5)=2.Step 6: Identify excluded edge
Edge (3-4)=6 is not chosen because (2-4)=5 is cheaper and connects 4 earlier.Final Answer:
Edge 3-4 with weight 6 -> Option DQuick Check:
Exclude heavier edge when cheaper path exists [OK]
- Including heavier edges when cheaper ones exist
- Not updating candidate edges after each addition
- Assuming all edges connected to MST are included
Ready to prove it?
Pass the test and this pattern moves unknown
