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^5See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI