Skip to main content
Minimum Spanning Tree

Prim's Algorithm

Start from any node. Repeatedly add the cheapest edge that connects a node in the tree to a node outside the tree. Use a min-heap to efficiently find the cheapest crossing edge. Grows the MST one node at a time.

O(E log V)
·
O(V)

How It Works

Prim's algorithm grows a minimum spanning tree outward from an arbitrary start node. Maintain a min-heap of candidate edges that cross from the tree to the rest of the graph. Repeatedly pop the cheapest crossing edge; if its far endpoint is not yet in the tree, add the node and the edge, then push all of that node's edges to non-tree neighbors. The cut property guarantees each cheapest crossing edge belongs to some MST, so V−1 accepted edges form an optimal tree.

With a binary heap and adjacency list the runtime is O(E log V) — every edge is pushed at most once and each heap operation costs O(log V). The structure mirrors Dijkstra almost line for line; the only difference is the heap key, which is the single edge weight rather than the accumulated path distance from the source.

Step-by-Step Visualization

Prim's MST: grow tree from node 0
0
0
1
1
2
2
3
3
MST{0}
Weight0
1/3

Code

Java
static int prim(List<int[]>[] graph, int n) {
  boolean[] visited = new boolean[n];
  PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] - b[0]);
  pq.add(new int[]{0, 0}); // [weight, node]
  int mstWeight = 0, count = 0;

  while (count < n) {
    int[] curr = pq.poll();
    int w = curr[0], u = curr[1];
    if (visited[u]) continue;
    visited[u] = true;
    mstWeight += w;
    count++;

    for (int[] edge : graph[u])
      if (!visited[edge[0]]) pq.add(new int[]{edge[1], edge[0]});
  }
  return mstWeight;
}

Tips & Gotchas

1Start from any node, grow MST by adding cheapest edge to a new node
2Use a min-heap of (weight, node) pairs
3Only add edges to unvisited nodes

Practice Problems

  • 1Min Cost to Connect All Points
  • 2Optimize Water Distribution in a Village
  • 3Minimum Cost to Connect Sticks

About the Minimum Spanning Tree Pattern

Connect all nodes in an undirected weighted graph with minimum total edge weight, using exactly V−1 edges (no cycles). Two classic algorithms: sort edges and add greedily (Kruskal's), or grow a tree from a node (Prim's).

Key insight

Start with: is it directed or undirected? Weighted or unweighted? Then pick the right tool: BFS for shortest unweighted path, Dijkstra for weighted, topological sort for DAG ordering, union-find for components.

Common Graphs Interview Problems

  • Number of Islands
  • Clone Graph
  • Course Schedule
  • Pacific Atlantic Water Flow
  • Network Delay Time
  • Minimum Spanning Tree
  • Word Ladder

Frequently Asked Questions

How does Prim's differ from Dijkstra when the code looks so similar?

Dijkstra's heap is keyed by total distance from the source and answers shortest-path questions; Prim's heap is keyed by the weight of a single crossing edge and answers minimum-connection questions. Mixing them up is a classic bug — an MST path between two nodes is generally not their shortest path.

Does the choice of starting node change the result?

The total weight of the MST is identical from any start. If several edges tie in weight, the specific set of chosen edges may differ, but all outcomes are valid minimum spanning trees. On dense graphs like complete point sets, Prim's O(V²) array variant can even beat the heap version.