Connecting Cities With Minimum Cost
1 approach, code in every language
Problem description
There are n cities labeled from 1 to n. You are given a list of connections, where each connection [a, b, cost] means city a and city b can be linked for the given cost.
Return the minimum total cost needed so that every pair of cities is connected, either directly or through other cities. If it is impossible to connect all cities, return -1.
Example 1
Input: n = 3, connections = [[1,2,5],[1,3,6],[2,3,1]]
Output: 6
Choosing the edges 2-3 (cost 1) and 1-2 (cost 5) links all three cities for a total of 6, the cheapest possible.
Example 2
Input: n = 4, connections = [[1,2,3],[3,4,4]]
Output: -1
Cities {1,2} and {3,4} form two separate groups with no edge between them, so full connectivity is impossible.
Constraints
1 <= n <= 10^41 <= connections.length <= 10^4connections[i].length == 31 <= xi, yi <= nxi != yi0 <= costi <= 10^5
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.
1,194 problems · 15,062 graded tests · free