Problem Description
You are given n cities and a list of connections where each connection specifies two cities and the cost to connect them. The goal is to connect all the cities with the minimum total cost. If it isn’t possible to connect all cities using the given connections, return -1.
Key Insights
- This is a Minimum Spanning Tree (MST) problem.
- Kruskal’s algorithm can be used by sorting the edges by cost and using a Union-Find (Disjoint Set Union) structure to efficiently check if adding an edge forms a cycle.
- Alternatively, Prim’s algorithm with a priority queue can solve this, but Kruskal’s is straightforward given edge-based input.
- The key is to add edges one by one in increasing order of cost until all cities are connected.
Space and Time Complexity
Time Complexity: O(E log E) due to sorting the connections, where E is the number of connections. Space Complexity: O(n) for the Union-Find data structure, plus O(E) space for storing the edges.
Solution
We use Kruskal's algorithm to build a Minimum Spanning Tree. First, sort the connections by cost. Then, iterate through each edge and use a Union-Find data structure to determine if the current edge connects two previously disconnected components. If it does, add the edge’s cost to the total cost and union the two components. Finally, if we have connected all n cities (i.e., used n-1 edges), return the total cost; otherwise, return -1.