Updated about 20 hours ago | GitHub
On this page

Connecting Cities With Minimum Cost

Problem Highlights

1: U-nderstand

Understand what the interviewer is asking for by using test cases and questions about the problem.

  • Established a set (2-3) of test cases to verify their own solution later.
  • Established a set (1-2) of edge cases to verify their solution handles complexities.
  • Have fully understood the problem and have no clarifying questions.
  • Have you verified any Time/Space Constraints for this problem?
  • How are the cities labeled?
    • From 1 to n, so arrays indexed by city need n + 1 slots.
  • Are the connections one-way?
    • No. Each [x, y, cost] connects x and y in both directions.
  • What should we return if the cities cannot all be connected?
    • Return -1.
  • What are we minimizing?
    • The total cost of the connections we choose, such that every pair of cities is joined by some path. That set of connections is a minimum spanning tree of the graph.
HAPPY CASE
Input: n = 3, connections = [[1,2,5],[1,3,6],[2,3,1]]
Output: 6
Explanation: Any two of the three connections link all three cities, so choose the two cheapest: [2,3,1] and [1,2,5].

Input: n = 4, connections = [[1,2,3],[2,3,1],[1,3,2],[3,4,4]]
Output: 7
Explanation: Take [2,3,1] and [1,3,2]. Skip [1,2,3], because cities 1 and 2 are already connected through city 3. Take [3,4,4], the only connection to city 4. 1 + 2 + 4 = 7.

EDGE CASE
Input: n = 4, connections = [[1,2,3],[3,4,4]]
Output: -1
Explanation: Even using every connection, cities 1 and 2 stay separated from cities 3 and 4.

Input: n = 4, connections = [[1,2,1],[2,3,1],[1,3,1]]
Output: -1
Explanation: There are 3 connections, which is the n - 1 a spanning tree needs, but none of them reaches city 4.

2: M-atch

Match what this problem looks like to known categories of problems, e.g. Linked List or Dynamic Programming, and strategies or patterns in those categories.

For graph problems, we want to consider the following approaches:

  • Union Find: At every single step, we use the shortest/cheapest route. The only issue will be, we might construct redundant routes. We use
    union find to avoid this issue. After we finish constructing the route, we can do one last check to make sure all the nodes are in this one single set. We can greedily pick the smallest edge at each iteration to connect cities together. Then, in the end, the result will be the smallest.
  • Dijkstra’s: Dijkstra’s algorithm finds the cheapest path from one source city to every other city. That is a different goal from finding the cheapest set of connections that links all the cities, so it does not solve this problem directly.
  • Prim’s: With Prim’s, the algorithm resembles Dijkstra’s algorithm. The MST is constructed starting from a single vertex and adding in new edges to the MST that link the partial tree to a new vertex outside of the MST
  • Kruskal’s: With Kruskal’s, we first sort all edges from smallest to largest weight, and then consider each edge in order. If the two endpoints of the edge are not yet in the same set, we keep the edge and merge the two sets; otherwise the edge would create a cycle, so we skip it. Union Find is the standard tool for tracking and merging these sets, which makes Kruskal’s a greedy algorithm built on Union Find.
  • BFS: We can use a queue for traversal. BFS can help us avoid processing a node more than once, because we can divide the vertices into two categories: Visited and Not visited. A boolean visited array is used to mark the visited vertices. For simplicity, it is assumed that all vertices are reachable from the starting vertex.

Note: Which one is better — Prims or Kruskal?
If the graph consists of lots of edges, i.e. for dense graphs, then Prim’s Algorithm is more efficient than Kruskal’s algorithm.

3: P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: If we model the cities and connections as a graph, each connection is an edge (undirected) and each city is a node of the graph. We need to find a subset of edges which connects all the nodes of the graph with the minimum possible total weight

1. Implement the Union find first, using union by size: the `forest` array stores the size of each root's set, and the smaller set is attached under the larger one
2. This is a greedy Algorithm, the way it works is every time you need to find the minimum cost from the connections and check if including this Edge would cause a loop or cycle, which is where our Union Find would come Handy.
3. Union Find Algo finds the parent of two cities and checks if they are not the same, because if they are then you are already forming a cycle that would violate the minimum spanning tree property so then our check helps over there.
4. After that, you can append the cost and in the end make these cities a new set using Union
5. At the end, return the total cost only if every city ended up in one set (exactly `n - 1` successful unions); otherwise return -1

⚠️ Common Mistakes

  • Deciding whether the cities are connected by counting the input connections (for example, connections.length < N - 1). Having at least N - 1 connections does not mean they reach every city: in the last edge case above, three connections form a cycle among cities 1, 2 and 3 and never reach city 4. Count the successful unions instead.
  • Sizing the Union Find arrays with N slots. The cities are labeled 1 to N, so the arrays need N + 1 slots.
  • Keeping an edge whose two cities already share a root. That edge closes a cycle and adds its cost without connecting anything new.

4: I-mplement

Implement the code to solve the algorithm.

class Solution:
    def minimumCost(self, N, connections):
        parent = [-1] * (N+1)
        forest = [1] * (N+1)
        self.n = N
        mst = []
        res = 0
        
        # build the graph
        for city1, city2, cost in sorted(connections, key = lambda x: x[2]):
            if self.find(parent, city1) != self.find(parent, city2):
                mst.append((city1, city2))
                res += cost
                if len(mst) == N:
                    break
                self.Union(forest, parent, city1, city2)
        return res if self.n == 1 else -1
                
    
    # traverse all the way to the top (root) going through the parent nodes
    def find(self, parent, i):
        while parent[i] != -1:
            i = parent[i]
        return i
    
    # start union implementation for disjoint set, returns false if elements have the same parent
    # this will help to prevent adding edge among elements from same parent, thus avoiding cycles
    def Union(self,forest, parent, x, y):
        set1 = self.find(parent, x)
        set2 = self.find(parent, y)
        
        if set1 != set2:
            if forest[set1] < forest[set2]:
                parent[set1] = set2
                forest[set2] += forest[set1]
            else:
                parent[set2] = set1
                forest[set1] += forest[set2]
        self.n-=1
class Solution {
    public int minimumCost(int N, int[][] connections) {
        // before the union, each city is considered as isolated, not-connected node, so there should be N unions at first 
	// 1 indexed, so need N+1 length
        UnionFind uf = new UnionFind(N + 1);
        // sort connections in a way that the cost is in ascending order 
        Arrays.sort(connections, new Comparator<int[]>(){
            public int compare(int[] a, int[] b){
                return a[2] - b[2];
            }                 
        });
       
        int cost = 0;
        int edgesUsed = 0;
        for(int i = 0; i < connections.length; i++) {
            int x = connections[i][0], y = connections[i][1];
            if(!uf.find(x, y)) {
                uf.union(x, y);
                cost += connections[i][2];
                edgesUsed++;
            }
        }
        // a spanning tree over N cities uses exactly N - 1 edges;
        // fewer successful unions means some city was never connected
        return edgesUsed == N - 1 ? cost : -1;
    }
    
    // each time we connect a city into the union, there will be one less isolated city
    class UnionFind {
        int[] array;
        public UnionFind(int size) {
            array = new int[size];
            for(int i = 0; i < size; i++) {
                array[i] = i;
            }
        }
        
        public int root(int i) {
            while(i != array[i]) {
                i = array[i];
            }
            return i;
        }
        
        public boolean find(int i, int j) {
            return root(i) == root(j);
        }
        
        public boolean union(int i, int j) {
            if(find(i, j)) return false;
            array[root(i)] = j;
            return true;
        }
    }
}

5: R-eview

Review the code by running specific example(s) and recording values (watchlist) of your code’s variables along the way.

  • Trace through your code with an input to check for the expected output
  • Catch possible edge cases and off-by-one errors

6: E-valuate

Evaluate the performance of your algorithm and state any strong/weak or future potential work.

Assume V is the number of cities (n) and E is the number of connections.

  • Time Complexity:
    • Python: O(E log E + E log V). Sorting the connections costs O(E log E). Union by size keeps every tree at most O(log V) tall, so each of the O(E) find calls costs O(log V).
    • Java: O(E log E + E * V) in the worst case. The sort is the same, but union points one root at the other city without comparing set sizes, and root does not compress paths, so a tree can grow into a chain of V nodes and a single root walk can take O(V) steps. Adding union by size, as the Python version does, brings each walk down to O(log V).
  • Space Complexity: O(V + E). The Union Find arrays take O(V). Sorting takes up to O(E): Python’s sorted() builds a new list of all E connections, and Java’s Arrays.sort on an object array can use up to E/2 temporary references.