Minimum Spanning Tree - Problem

Given a weighted undirected graph, implement Kruskal's algorithm to find the minimum spanning tree (MST). The graph is represented as a list of edges, where each edge contains two vertices and a weight.

A minimum spanning tree is a subset of edges that connects all vertices with the minimum total weight and contains no cycles. The result should be a list of edges in the MST.

Return the edges of the MST as a list of [u, v, weight] arrays, sorted by weight in ascending order.

Input & Output

Example 1 — Simple Triangle Graph
$ Input: edges = [[0,1,1],[1,2,2],[0,2,3]]
Output: [[0,1,1],[1,2,2]]
💡 Note: Three vertices (0,1,2) with edges: (0,1):1, (1,2):2, (0,2):3. The MST uses the two cheapest edges (0,1):1 and (1,2):2 with total weight 3. Edge (0,2):3 would create a cycle.
Example 2 — Four Vertex Graph
$ Input: edges = [[0,1,4],[0,2,1],[1,2,2],[1,3,5],[2,3,3]]
Output: [[0,2,1],[1,2,2],[2,3,3]]
💡 Note: Four vertices need 3 edges for MST. Sorted by weight: (0,2):1, (1,2):2, (2,3):3, (0,1):4, (1,3):5. Take first 3 edges that don't create cycles: (0,2):1, (1,2):2, (2,3):3. Total weight: 6.
Example 3 — Linear Chain
$ Input: edges = [[0,1,1],[1,2,1],[2,3,1]]
Output: [[0,1,1],[1,2,1],[2,3,1]]
💡 Note: Linear chain graph where all edges have equal weight 1. All edges are needed for MST since no cycles exist. Total weight: 3.

Constraints

  • 1 ≤ edges.length ≤ 1000
  • 0 ≤ u, v ≤ 100
  • 1 ≤ weight ≤ 1000
  • The graph is connected

Visualization

Tap to expand
INPUT GRAPHKRUSKAL'S ALGORITHMFINAL MST012123All edges with weightsEdges: [0,1,1], [1,2,2], [0,2,3]1Sort by weight2Union-Find check3Add if no cycle4Stop at n-1 edgesTime: O(m log m)01212MST Complete!Edges: [[0,1,1], [1,2,2]]Total weight: 3Key Insight:Greedily selecting the cheapest edges while avoiding cycles (using Union-Find) guarantees the minimum spanning tree.TutorialsPoint - Minimum Spanning Tree | Kruskal's Algorithm
Asked in
Google 45 Amazon 38 Microsoft 32 Apple 28
34.5K Views
Medium Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen