{x}
blog image

Connecting Cities With Minimum Cost

Solution Explanation: Minimum Cost to Connect Cities

This problem asks for the minimum cost to connect n cities using a given set of connections, where each connection specifies two cities and its cost. This is a classic Minimum Spanning Tree (MST) problem. The most efficient way to solve it is using Kruskal's Algorithm.

Kruskal's Algorithm

Kruskal's algorithm is a greedy approach that iteratively adds edges to the MST while ensuring no cycles are formed. It works as follows:

  1. Sort Edges: Sort all connections by their cost in ascending order.
  2. Union-Find: Use a Union-Find data structure (Disjoint Set Union) to track connected components. Initially, each city is its own component.
  3. Iterate and Merge: Iterate through the sorted connections. For each connection:
    • Check if the two cities are already in the same component using find() (Union-Find).
    • If they are not in the same component, it means adding this edge won't create a cycle. Merge the components using union() (Union-Find), add the edge's cost to the total cost, and decrement the number of connected components.
  4. Termination: Continue until either all cities are connected (number of components is 1) or all edges are processed.

Union-Find (Disjoint Set Union) efficiently determines connectivity and merges components. The find() operation determines the root of a component, and union() merges two components by setting the root of one to the root of the other.

Time Complexity Analysis

  • Sorting: Sorting the edges takes O(m log m) time, where 'm' is the number of connections.
  • Union-Find: find() and union() operations in a Union-Find data structure take effectively amortized O(α(n)) time, where α(n) is the inverse Ackermann function, which grows extremely slowly and can be considered practically constant for all realistic input sizes. We perform these operations at most 'm' times.
  • Iteration: Iterating through the edges takes O(m) time.

Therefore, the overall time complexity is dominated by sorting: O(m log m).

Space Complexity Analysis

  • Union-Find: The Union-Find data structure requires O(n) space, where 'n' is the number of cities.
  • Sorted Edges: Storing the sorted connections might require O(m) space in some implementations.

The overall space complexity is O(n + m).

Code Examples (Python, Java, C++, Go, TypeScript)

The provided code snippets in different languages implement Kruskal's algorithm efficiently using Union-Find. They follow the steps outlined above. Note that the Union-Find implementation varies slightly across languages but the core functionality remains the same. The Python, Java, C++, and Go examples all have very similar structures, with only syntax varying between them. The TypeScript code is very similar as well. Each example correctly handles the case where not all cities can be connected by returning -1.