0
Leetcode Problem 1135. Connecting Cities With Minimum Cost
1135. Connecting Cities With Minimum Cost
AI Mock Interview
Leetcode Solutions
Minimum Spanning Tree (Using Kruskal's algorithm)
Solution Idea
Algorithm Steps
Code Implementation
Complexity Analysis
Sort the connections array based on the cost in ascending order.
Initialize a Disjoint Set Union-Find structure with each city as a separate set.
Iterate over the sorted connections.
For each connection, use the Union-Find structure to check if the cities are already connected.
If they are not connected, union them and add the cost to the total cost.
Keep track of the number of edges added to the MST.
If the number of edges added equals
n - 1
, all cities are connected, and we return the total cost.
If we finish iterating through connections without connecting all cities, return -1.
Minimum Spanning Tree (Using Prim's algorithm)
Ask Question
Programming Language
Purpose:
General Question
Debug My Code
image/screenshot of info
(optional)
[+]
Full Screen
Loading...
Get Answer
Suggested Answer
Answer
Full Screen
Copy Answer Code
Loading...