Skip to problem
←

Minimum Spanning Tree with Prim’s Algorithm

Medium 0 attempts

Given a connected, weighted, undirected graph with V vertices numbered 0 through V - 1, use Prim's algorithm to return the total weight of a minimum spanning tree.

A spanning tree connects every vertex using exactly V - 1 edges and contains no cycle. Among all such trees, choose one with the smallest sum of edge weights. Return only that sum; several different trees may have the same minimum weight.

The adjacency list adj[u] contains pairs [neighbor, weight]. Each undirected edge appears in both endpoint lists, but its weight is counted only once when selected. A single vertex requires no edges, so its answer is 0.

In the first example, select edges 0–1 with weight 1 and 1–2 with weight 2. Their total is 3; selecting the remaining edge as well would create a cycle.

Function contract

Implement primMST(V, adj).

Output: Return the minimum total weight of edges connecting all vertices without a cycle.

Example 1

Input
V = 3
adj = [[[1,1],[2,3]],[[0,1],[2,2]],[[0,3],[1,2]]]
Output
3

Example 2

Input
V = 1
adj = [[]]
Output
0
Constraints
  • 1 <= V <= 1000
  • The graph is connected and undirected.
  • adj[u] lists [neighbor, weight] pairs; each edge appears in both endpoint lists.
  • 1 <= weight <= 10^5
  • Vertices are numbered 0 through V - 1; adj.length equals V.
  • The graph has no self-loops or parallel edges.

Prim's Algorithm with Linear Minimum Selection

Maintain key[v], the cheapest edge currently known from the selected tree to unvisited vertex v. Set vertex 0's key to zero so it becomes the initial vertex without adding an edge cost.

Repeatedly choose the unvisited vertex with the smallest key, add that key to the total, and mark the vertex visited. For each unvisited neighbor, improve its key if the current edge is cheaper. A key is a single connecting edge's weight, not a distance from the starting vertex.

The minimum crossing edge is safe to add: if a minimum spanning tree does not contain it, inserting it creates a cycle, and another edge crossing the same cut can be removed without increasing the total weight. This preserves the possibility of an optimal tree at every step.

The graph is guaranteed connected, so every selected vertex has a finite key. Updating only unvisited vertices prevents cycles and counts each selected undirected edge once.

javascript
function primMST(V, adj) {
  const visited = Array(V).fill(false),
    key = Array(V).fill(Infinity);
  key[0] = 0;
  let totalWeight = 0;
  for (let count = 0; count < V; count++) {
    let u = -1;
    for (let i = 0; i < V; i++)
      if (!visited[i] && (u === -1 || key[i] < key[u])) u = i;
    visited[u] = true;
    totalWeight += key[u];
    for (const [v, w] of adj[u]) if (!visited[v] && w < key[v]) key[v] = w;
  }
  return totalWeight;
}

Time: O(V² + E) for this implementation | Space: O(V)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript