Minimum Spanning Tree Prim's Algorithm in DSA Java - Time & Space Complexity
We want to understand how the time taken by Prim's algorithm grows as the graph size increases.
Specifically, how the number of nodes and edges affects the work done.
Analyze the time complexity of the following Prim's algorithm code snippet.
int primMST(int graph[][], int V) {
int[] key = new int[V];
boolean[] mstSet = new boolean[V];
Arrays.fill(key, Integer.MAX_VALUE);
key[0] = 0;
for (int count = 0; count < V - 1; count++) {
int u = minKey(key, mstSet, V);
mstSet[u] = true;
for (int v = 0; v < V; v++) {
if (graph[u][v] != 0 && !mstSet[v] && graph[u][v] < key[v]) {
key[v] = graph[u][v];
}
}
}
return Arrays.stream(key).sum();
}
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 run roughly V x V times.
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(V2)
This means the time grows proportional to 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 depends on V squared when using an adjacency matrix.
Understanding this time complexity helps you explain how graph size affects algorithm speed and why data structures matter.
"What if we used a priority queue and adjacency list instead of an adjacency matrix? How would the time complexity change?"
Practice
Solution
Step 1: Understand Prim's Algorithm purpose
Prim's Algorithm builds a tree connecting all vertices with the smallest sum of edge weights.Step 2: Compare with other graph tasks
It is not for shortest path, cycle detection, or sorting vertices.Final Answer:
To find the minimum spanning tree connecting all vertices with minimum total edge weight -> Option DQuick Check:
Prim's Algorithm = Minimum Spanning Tree [OK]
- Confusing Prim's with Dijkstra's algorithm
- Thinking it finds shortest paths
- Assuming it detects cycles
Solution
Step 1: Understand key array initialization
Key array stores minimum edge weights to vertices; initialize with max values except start vertex 0 with 0.Step 2: Check each option
int[] key = new int[5]; Arrays.fill(key, Integer.MAX_VALUE); key[0] = 0; correctly sets all to Integer.MAX_VALUE and start vertex key[0] to 0.Final Answer:
int[] key = new int[5]; Arrays.fill(key, Integer.MAX_VALUE); key[0] = 0; -> Option CQuick Check:
Initialize keys with max except start = 0 [OK]
- Setting all keys to 0
- Setting start vertex key to max value
- Incorrect order of fill and assignment
int[][] graph = {
{0, 2, 0, 6},
{2, 0, 3, 8},
{0, 3, 0, 0},
{6, 8, 0, 0}
};
Solution
Step 1: Start from vertex 0 and pick minimum edges
Edges chosen: 0-1 (2), 1-2 (3), 0-3 (6)Step 2: Sum the weights of chosen edges
Total weight = 2 + 3 + 6 = 11Final Answer:
11 -> Option BQuick Check:
Sum edges 2+3+6 = 11 [OK]
- Choosing wrong edges ignoring minimum weight
- Adding edges that form cycles
- Starting from wrong vertex
int minKey(int[] key, boolean[] mstSet) {
int min = Integer.MAX_VALUE, minIndex = -1;
for (int v = 0; v < key.length; v++) {
if (!mstSet[v] && key[v] < min) {
min = key[v];
minIndex = v;
}
}
return minIndex;
}
// Usage in main loop:
int u = minKey(key, mstSet);
mstSet[u] = true;
Solution
Step 1: Analyze minKey function logic
It finds vertex with smallest key not yet included in MST correctly.Step 2: Check initialization and loop
minIndex = -1 is correct to detect no valid vertex; loop from 0 covers all vertices.Final Answer:
No error; code correctly finds vertex with minimum key not in MST -> Option AQuick Check:
minKey returns correct vertex index [OK]
- Changing minIndex initialization incorrectly
- Changing return type wrongly
- Starting loop from 1 misses vertex 0
0-1: 3, 0-3: 1, 1-2: 7, 1-4: 5, 2-4: 2, 3-4: 4, 3-5: 6, 4-5: 8Using Prim's Algorithm starting from vertex 0, what is the total weight of the minimum spanning tree?
Solution
Step 1: Start from vertex 0 and pick minimum edges stepwise
Edges chosen: 0-3 (1), 0-1 (3), 3-4 (4), 4-2 (2), 3-5 (6)Step 2: Sum the weights of chosen edges
Total weight = 1 + 3 + 4 + 2 + 6 = 16Step 3: Check for better MST
Replacing 3-5 (6) with 4-5 (8) is heavier; so total is 16Final Answer:
16 -> Option AQuick Check:
Sum edges 1+3+4+2+6 = 16 [OK]
- Choosing heavier edges unnecessarily
- Missing to update keys after adding vertices
- Not starting from vertex 0
Ready to prove it?
Pass the test and this pattern moves unknown
