Minimum Spanning Tree Prim's Algorithm in DSA Go - 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.
Specifically, how does the number of steps grow when the graph has more nodes and edges?
Analyze the time complexity of the following Prim's algorithm code snippet.
func primMST(graph [][]int) int {
n := len(graph)
visited := make([]bool, n)
dist := make([]int, n)
for i := range dist {
dist[i] = 1_000_000_000
}
dist[0] = 0
totalWeight := 0
for i := 0; i < n; i++ {
u := -1
for v := 0; v < n; v++ {
if !visited[v] && (u == -1 || dist[v] < dist[u]) {
u = v
}
}
visited[u] = true
totalWeight += dist[u]
for v := 0; v < n; v++ {
if graph[u][v] != 0 && !visited[v] && graph[u][v] < dist[v] {
dist[v] = graph[u][v]
}
}
}
return totalWeight
}
This code finds the minimum spanning tree weight of a graph using Prim's algorithm with an adjacency matrix.
Look at the loops that repeat work:
- Primary operation: The outer loop runs once for each node (n times).
- Inside it: There are two inner loops each running n times.
- Dominant work: The nested loops checking all nodes to find the minimum distance and update distances.
For each of the n nodes, we do two loops over n nodes, so roughly n * (n + n) = 2n² operations.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 200 |
| 100 | About 20,000 |
| 1000 | About 2,000,000 |
Pattern observation: The operations grow roughly with the square of the number of nodes.
Time Complexity: O(n²)
This means if the number of nodes doubles, the time to run the algorithm roughly quadruples.
[X] Wrong: "Prim's algorithm always runs in linear time O(n)."
[OK] Correct: Because Prim's algorithm checks all nodes repeatedly, the time grows with the square of nodes when using a simple adjacency matrix and no advanced data structures.
Understanding how Prim's algorithm scales helps you explain your choices and shows you know how to handle graphs efficiently in real problems.
"What if we used a priority queue (min-heap) to select the next node instead of scanning all nodes? 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 algorithms
Shortest path and cycle detection are different problems; Prim's focuses on minimum spanning tree.Final Answer:
To find the minimum spanning tree connecting all vertices with minimum total edge weight -> Option AQuick 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: Check correct priority queue initialization in Go
PriorityQueue is usually a slice; make with length 0 and call heap.Init(&pq) to initialize.Step 2: Analyze other options
pq := PriorityQueue{}; pq.Init() misses heap.Init call; C sets pq to nil; D uses slice but sorts, not heap.Final Answer:
pq := make(PriorityQueue, 0); heap.Init(&pq) -> Option CQuick Check:
Use make + heap.Init for priority queue [OK]
- Forgetting to call heap.Init
- Setting priority queue to nil
- Sorting slice instead of using heap
edges := [][]int{{0,1,2},{1,2,3},{0,2,1}}
// Graph with 3 vertices and edges with weights
// What is the total weight of the minimum spanning tree printed by this code?
func primMST() int {
n := 3
graph := make([][]Edge, n)
for _, e := range edges {
graph[e[0]] = append(graph[e[0]], Edge{to: e[1], weight: e[2]})
graph[e[1]] = append(graph[e[1]], Edge{to: e[0], weight: e[2]})
}
visited := make([]bool, n)
pq := &PriorityQueue{}
heap.Init(pq)
heap.Push(pq, &Item{vertex: 0, weight: 0})
total := 0
for pq.Len() > 0 {
item := heap.Pop(pq).(*Item)
if visited[item.vertex] {
continue
}
visited[item.vertex] = true
total += item.weight
for _, e := range graph[item.vertex] {
if !visited[e.to] {
heap.Push(pq, &Item{vertex: e.to, weight: e.weight})
}
}
}
return total
}
Solution
Step 1: Build the graph and list edges
Edges: (0-1)=2, (1-2)=3, (0-2)=1. Start from vertex 0 with weight 0.Step 2: Run Prim's Algorithm step-by-step
Pick 0 (weight 0), add edges (0-1:2), (0-2:1). Next pick edge with smallest weight: (0-2:1), total=1. Then pick (0-1:2), total=3. Vertex 1 and 2 visited, done.Final Answer:
3 -> Option AQuick Check:
Sum edges 1 + 2 = 3 [OK]
- Adding all edges instead of minimum spanning tree
- Starting from wrong vertex
- Counting edges twice
func primBuggy() int {
n := 3
graph := make([][]Edge, n)
// edges omitted for brevity
visited := make([]bool, n)
pq := &PriorityQueue{}
heap.Init(pq)
heap.Push(pq, &Item{vertex: 0, weight: 0})
total := 0
for pq.Len() > 0 {
item := heap.Pop(pq).(*Item)
if visited[item.vertex] {
total += item.weight
continue
}
visited[item.vertex] = true
for _, e := range graph[item.vertex] {
if !visited[e.to] {
heap.Push(pq, &Item{vertex: e.to, weight: e.weight})
}
}
}
return total
}
Solution
Step 1: Identify where total is updated
Total is increased only when visited[item.vertex] is true, which means vertex already visited.Step 2: Understand why this is wrong
Weights should be added only when vertex is visited first time, not when skipping duplicates.Final Answer:
Adding edge weight after skipping visited vertex causes incorrect total -> Option BQuick Check:
Update total only on first visit [OK]
- Adding weights multiple times for same vertex
- Forgetting to call heap.Init
- Not marking visited vertices
(0-1, 2), (0-3, 6), (1-2, 3), (1-3, 8), (1-4, 5), (2-4, 7), (3-4, 9)Using 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 smallest edges stepwise
Start at 0: edges (0-1:2), (0-3:6). Pick (0-1:2), total=2.Step 2: Add edges from visited vertices and pick minimum
Visited: 0,1. Edges: (1-2:3), (1-3:8), (1-4:5), (0-3:6). Pick (1-2:3), total=5.Step 3: Continue adding minimum edges connecting new vertices
Visited: 0,1,2. Edges: (1-3:8), (1-4:5), (0-3:6), (2-4:7). Pick (1-4:5), total=10.Step 4: Add edges from new vertex 4
Visited: 0,1,2,4. Edges: (1-3:8), (0-3:6), (2-4:7), (3-4:9). Pick (0-3:6), total=16.Step 5: Add last vertex 3
Visited all vertices. Total weight = 16.Final Answer:
16 -> Option DQuick Check:
Sum edges 2+3+5+6 = 16 [OK]
- Choosing edges with larger weights first
- Not updating visited vertices correctly
- Counting edges twice
Ready to prove it?
Pass the test and this pattern moves unknown
