Connecting Cities With Minimum Cost - Problem
Imagine you're a city planner tasked with connecting
Given an integer
Your goal is to find the minimum total cost to connect all cities such that there's at least one path between every pair of cities. If it's impossible to connect all cities, return
This is a classic Minimum Spanning Tree (MST) problem!
n cities with the minimum possible cost. You have a list of potential connections between cities, each with a specific cost to build.Given an integer
n representing the number of cities (labeled 1 to n) and an array connections where connections[i] = [xi, yi, costi] represents the cost to build a bidirectional road between city xi and city yi.Your goal is to find the minimum total cost to connect all cities such that there's at least one path between every pair of cities. If it's impossible to connect all cities, return
-1.This is a classic Minimum Spanning Tree (MST) problem!
Input & Output
example_1.py โ Basic Triangle
$
Input:
n = 3, connections = [[1,2,5],[1,3,6],[2,3,1]]
โบ
Output:
6
๐ก Note:
We can connect all 3 cities by choosing edges (2,3) with cost 1 and (1,2) with cost 5, for a total cost of 6. The edge (1,3) with cost 6 is not needed as cities 1 and 3 are already connected through city 2.
example_2.py โ Impossible Connection
$
Input:
n = 4, connections = [[1,2,3],[3,4,4]]
โบ
Output:
-1
๐ก Note:
We cannot connect all 4 cities because cities 1,2 form one connected component and cities 3,4 form another, but there's no edge connecting these two components.
example_3.py โ Linear Chain
$
Input:
n = 4, connections = [[1,2,1],[2,3,2],[3,4,3],[1,4,10],[2,4,5]]
โบ
Output:
6
๐ก Note:
The minimum spanning tree uses edges (1,2) cost=1, (2,3) cost=2, and (3,4) cost=3, giving total cost 6. Other edges like (1,4) cost=10 and (2,4) cost=5 are more expensive alternatives.
Visualization
Tap to expand
Understanding the Visualization
1
Survey All Routes
List all possible railway connections with their construction costs
2
Sort by Cost
Arrange routes from cheapest to most expensive
3
Build Greedily
Start with the cheapest route and keep adding routes that connect new regions
4
Avoid Redundancy
Skip routes that would create loops - they waste money without improving connectivity
Key Takeaway
๐ฏ Key Insight: Kruskal's algorithm greedily selects minimum cost edges while avoiding cycles, guaranteed to produce the optimal Minimum Spanning Tree.
Time & Space Complexity
Time Complexity
O(2^E * N)
We try 2^E combinations of edges, and for each we do O(N) connectivity check
โ Linear Growth
Space Complexity
O(E + N)
Space for storing connections and visited arrays during connectivity checks
โ Linear Space
Constraints
- 1 โค n โค 104
- 1 โค connections.length โค 104
- connections[i].length == 3
- 1 โค xi, yi โค n
- xi โ yi
- 0 โค costi โค 105
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code