Minimum Spanning Tree Prim's Algorithm in DSA Javascript - 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 implementation using an adjacency matrix.
function primMST(graph) {
const n = graph.length;
const selected = Array(n).fill(false);
selected[0] = true;
let edgesCount = 0;
while (edgesCount < n - 1) {
let min = Infinity;
let x = 0, y = 0;
for (let i = 0; i < n; i++) {
if (selected[i]) {
for (let j = 0; j < n; j++) {
if (!selected[j] && graph[i][j] < min) {
min = graph[i][j];
x = i;
y = j;
}
}
}
}
selected[y] = true;
edgesCount++;
}
}
This code finds the minimum spanning tree of a graph represented by a matrix, by repeatedly adding the smallest edge connecting selected nodes to unselected nodes.
Look for loops and repeated steps that take most time.
- Primary operation: Nested loops scanning all edges between selected and unselected nodes.
- How many times: Outer while loop runs (n - 1) times; inside, two nested for loops each run n times.
As the number of nodes (n) grows, the algorithm checks many edges repeatedly.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 * 10 * 9 = 900 |
| 100 | About 100 * 100 * 99 = 990,000 |
| 1000 | About 1000 * 1000 * 999 = 999,000,000 |
Pattern observation: The operations grow roughly with the cube of n, so the work increases very fast as the graph gets bigger.
Time Complexity: O(n^3)
This means the time needed grows roughly with the cube of the number of nodes, so doubling nodes makes the work about eight times bigger.
[X] Wrong: "Prim's algorithm always runs in O(n^2) time regardless of implementation."
[OK] Correct: The time depends on how the graph is stored and how edges are searched. Using an adjacency matrix with nested loops leads to O(n^3) time, not O(n^2).
Understanding how Prim's algorithm scales helps you explain your choices and shows you know how data structures affect performance.
"What if we used a priority queue and adjacency list instead of a matrix? 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 algorithms
Shortest path algorithms find paths, cycle detection finds loops, and topological sort orders nodes. These are different from Prim's goal.Final Answer:
To find the minimum spanning tree of a connected weighted graph -> Option DQuick Check:
Prim's Algorithm = Minimum Spanning Tree [OK]
- Confusing Prim's with shortest path algorithms
- Thinking it detects cycles
- Mixing it with topological sorting
Solution
Step 1: Understand key array purpose
The key array holds the minimum edge weight to connect each vertex. It starts with Infinity except the first vertex which is 0.Step 2: Check initialization syntax
Using new Array(5).fill(Infinity) sets all to Infinity, then key[0] = 0 sets start vertex correctly.Final Answer:
const key = new Array(5).fill(Infinity); key[0] = 0; -> Option CQuick Check:
Key array init with Infinity except start = 0 [OK]
- Filling key array with zeros instead of Infinity
- Setting start vertex key to Infinity
- Using null or -1 which breaks comparisons
const graph = [ [0, 2, 0, 6], [2, 0, 3, 8], [0, 3, 0, 0], [6, 8, 0, 0] ];If Prim's Algorithm starts from vertex 0, what is the order of vertices added to the MST?
Solution
Step 1: Start from vertex 0
Initialize MST with vertex 0. Adjacent edges: 0-1 (2), 0-3 (6).Step 2: Choose minimum edge from MST
Edge 0-1 has weight 2, edge 0-3 has weight 6. Choose vertex 1 next.Step 3: Update edges from MST vertices (0,1)
Edges: 1-2 (3), 1-3 (8), 0-3 (6). Minimum is 1-2 (3) vs 0-3 (6). Choose vertex 2 next.Step 4: Add vertex 2 and update edges
Edges from MST (0,1,2): 0-3 (6), 1-3 (8), 2-3 (0). Minimum is 0-3 (6). Add vertex 3 last.Final Answer:
[0, 1, 3, 2] -> Option BQuick Check:
Prim's MST order = [0, 1, 3, 2] [OK]
- Choosing edges with zero weight as valid connections
- Not updating edges after adding vertices
- Adding vertices in wrong order ignoring minimum edge
function primMST(graph) {
const V = graph.length;
const key = new Array(V).fill(Infinity);
const mstSet = new Array(V).fill(false);
key[0] = 0;
for (let count = 0; count < V - 1; count++) {
let u = minKey(key, mstSet);
mstSet[u] = true;
for (let v = 0; v < V; v++) {
if (graph[u][v] && !mstSet[v] && graph[u][v] < key[v]) {
key[v] = graph[u][v];
}
}
}
return key;
}
function minKey(key, mstSet) {
let min = Infinity, minIndex = -1;
for (let v = 0; v < key.length; v++) {
if (!mstSet[v] && key[v] < min) {
min = key[v];
minIndex = v;
}
}
return minIndex;
}
Solution
Step 1: Analyze code functionality
The code updates key values and mstSet correctly but only returns key array, not MST edges.Step 2: Identify missing MST structure
Prim's Algorithm requires tracking parent nodes to know which edges form the MST. This code lacks parent tracking.Final Answer:
The function does not track parent nodes to build MST edges -> Option AQuick Check:
Missing parent array means MST edges unknown [OK]
- Assuming key array alone gives MST edges
- Ignoring need for parent array
- Thinking minKey returning -1 causes error here
const graph = {
0: [{node:1, weight:4}, {node:7, weight:8}],
1: [{node:0, weight:4}, {node:2, weight:8}, {node:7, weight:11}],
2: [{node:1, weight:8}, {node:3, weight:7}, {node:5, weight:4}, {node:8, weight:2}],
3: [{node:2, weight:7}, {node:4, weight:9}, {node:5, weight:14}],
4: [{node:3, weight:9}, {node:5, weight:10}],
5: [{node:2, weight:4}, {node:3, weight:14}, {node:4, weight:10}, {node:6, weight:2}],
6: [{node:5, weight:2}, {node:7, weight:1}, {node:8, weight:6}],
7: [{node:0, weight:8}, {node:1, weight:11}, {node:6, weight:1}, {node:8, weight:7}],
8: [{node:2, weight:2}, {node:6, weight:6}, {node:7, weight:7}]
};
If you run Prim's Algorithm starting from vertex 0, which edge will be added last to the MST?Solution
Step 1: Understand MST construction order
Prim's Algorithm adds edges with smallest weights connecting new vertices to MST.Step 2: Identify heavy edges likely added last
Edges with large weights like 9, 11, 10, 7 are candidates for last addition.Step 3: Trace MST growth
Starting from 0: add 1 (0-1:4), 2 (1-2:8), 8 (2-8:2), 5 (2-5:4), 6 (5-6:2), 7 (6-7:1), 3 (2-3:7), and finally 4 (3-4:9).Final Answer:
Edge between vertices 3 and 4 with weight 9 -> Option AQuick Check:
Largest edge weight added last in Prim's MST [OK]
- Assuming edges with weight 7 or 10 are last
- Ignoring that MST adds smallest edges first
- Confusing adjacency list with matrix
Ready to prove it?
Pass the test and this pattern moves unknown
