Back to Practice
#0287
Minimum Spanning Tree Cost
HardDSA40 min25 XP
Problem
Given n nodes labeled 0 to n-1 and undirected weighted edges [u, v, w], return the minimum cost to connect every node, or -1 if impossible.
Why This Matters
MST problems combine greedy sorting with union-find, two patterns that often appear together.
Function Signature
def minimum_spanning_tree_cost(n, edges):
Examples
Example 1
Inputn = 4, edges = [[0,1,1],[1,2,2],[0,2,4],[2,3,1]]
Output4
Use edges 0-1, 2-3, and 1-2 for total cost 4.
Constraints
- Return the exact requested value.
- Handle edge cases cleanly.
- Use the intended DSA pattern when brute force would scale poorly.
CodePython
Visible browser tests run here when available.
Testcases2 visible / 3 hidden categories
Connected graph
Input4 nodes
Expected4
The three cheapest non-cycling edges connect all nodes.
Disconnected graph
Input3 nodes one edge
Expected-1
Node 2 cannot be connected.
Hidden Test Categories
already tree-shaped graphduplicate edgescycle-heavy graph