
Problem
Solution
Submissions
Minimum Spanning Tree (MST)
Certification: Advanced Level
Accuracy: 66.67%
Submissions: 3
Points: 15
Write a Python function that implements Kruskal's algorithm to find a connected, undirected graph's Minimum Spanning Tree (MST). The MST is a subset of the edges that connects all vertices with the minimum possible total edge weight.
Example 1
- Input: Edges = [(0, 1, 10), (0, 2, 6), (0, 3, 5), (1, 3, 15), (2, 3, 4)], Vertices = 4
- Output: [(2, 3, 4), (0, 3, 5), (0, 2, 6)]
- Explanation:
- Step 1: Sort all edges in non-decreasing order by weight: (2,3,4), (0,3,5), (0,2,6), (0,1,10), (1,3,15).
- Step 2: Pick edges one by one and add to MST if they don't form a cycle.
- Step 3: First edge (2,3,4) is added.
- Step 4: Second edge (0,3,5) is added.
- Step 5: Third edge (0,2,6) is added.
- Step 6: No need to add more edges as all vertices are already connected.
- Step 7: The MST consists of edges [(2,3,4), (0,3,5), (0,2,6)] with total weight 15.
Example 2
- Input: Edges = [(0, 1, 4), (0, 2, 3), (1, 2, 1), (1, 3, 2), (2, 3, 4)], Vertices = 4
- Output: [(1, 2, 1), (1, 3, 2), (0, 2, 3)]
- Explanation:
- Step 1: Sort all edges in non-decreasing order by weight: (1,2,1), (1,3,2), (0,2,3), (0,1,4), (2,3,4).
- Step 2: Pick edges one by one and add to MST if they don't form a cycle.
- Step 3: First edge (1,2,1) is added.
- Step 4: Second edge (1,3,2) is added.
- Step 5: Third edge (0,2,3) is added.
- Step 6: No need to add more edges as all vertices are already connected.
- Step 7: The MST consists of edges [(1,2,1), (1,3,2), (0,2,3)] with total weight 6.
Constraints
- 1 ≤ number of vertices ≤ 10^5
- 0 ≤ number of edges ≤ 10^6
- 1 ≤ edge weights ≤ 10^6
- Graph is connected
- Time Complexity: O(E log E), where E is the number of edges
- Space Complexity: O(V + E), where V is the number of vertices and E is the number of edges
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Sort all edges in non-decreasing order of their weight
- Use a disjoint set (Union-Find) data structure to detect cycles
- Process edges in order of increasing weight
- For each edge, if including it doesn't form a cycle, add it to the MST
- Return the list of edges in the MST