Connecting Cities With Minimum Cost in Pytho

Connecting cities with minimum cost is a classic Minimum Spanning Tree (MST) problem. Given N cities and connections with costs, we need to find the minimum cost to connect all cities. This can be solved using Kruskal's algorithm with a Union-Find data structure.

Problem Understanding

We have N cities numbered from 1 to N, and connections where each connection [city1, city2, cost] represents the cost to connect two cities. We need to find the minimum cost to ensure every pair of cities has a path between them ?

1 2 3 5 6 1

Algorithm Steps

The solution uses Kruskal's algorithm with Union-Find:

  • Sort all connections by cost in ascending order

  • Use Union-Find to detect cycles and merge components

  • Add edges with minimum cost that don't create cycles

  • Continue until all cities are connected

Implementation

class Solution:
    def find(self, x):
        """Find root of element x with path compression"""
        if self.parent[x] == -1:
            return x
        self.parent[x] = self.find(self.parent[x])
        return self.parent[x]
    
    def union(self, x, y):
        """Union two sets containing x and y"""
        parent_x = self.find(x)
        parent_y = self.find(y)
        if parent_x == parent_y:
            return
        self.parent[parent_y] = parent_x
    
    def minimumCost(self, n, connections):
        """Find minimum cost to connect all cities"""
        self.parent = [-1 for i in range(n + 1)]
        remaining_edges = n - 1  # Need n-1 edges for MST
        total_cost = 0
        
        # Sort connections by cost
        connections.sort(key=lambda x: x[2])
        
        for connection in connections:
            city1, city2, cost = connection
            
            # If cities are not connected, connect them
            if self.find(city1) != self.find(city2):
                self.union(city1, city2)
                total_cost += cost
                remaining_edges -= 1
                
                # If all cities connected, return cost
                if remaining_edges == 0:
                    return total_cost
        
        # If not all cities can be connected
        return -1

# Example usage
solution = Solution()

# Test case 1: Cities can be connected
print(solution.minimumCost(3, [[1,2,5], [1,3,6], [2,3,1]]))

# Test case 2: All cities already connected optimally  
print(solution.minimumCost(4, [[1,2,3], [3,4,4]]))
6
-1

How It Works

The algorithm works by:

  1. Sorting: Connections are sorted by cost to always consider cheapest options first

  2. Union-Find: Tracks which cities are already connected to avoid cycles

  3. Greedy Selection: Adds the cheapest edge that connects two separate components

  4. Early Termination: Stops when all cities are connected (n-1 edges added)

Time and Space Complexity

Aspect Complexity Reason
Time O(E log E) Sorting connections dominates
Space O(N) Parent array for Union-Find

Where E is the number of connections and N is the number of cities.

Conclusion

This problem demonstrates Kruskal's algorithm for finding Minimum Spanning Trees. The Union-Find data structure efficiently detects cycles while the greedy approach ensures optimal cost selection.

Updated on: 2026-03-25T08:22:13+05:30

490 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements