Connecting Cities With Minimum Cost - Problem

There are n cities labeled from 1 to n. You are given the integer n and an array connections where connections[i] = [xi, yi, costi] indicates that the cost of connecting city xi and city yi (bidirectional connection) is costi.

Return the minimum cost to connect all the n cities such that there is at least one path between each pair of cities. If it is impossible to connect all the n cities, return -1.

The cost is the sum of the connections' costs used.

Input & Output

Example 1 — Basic Connected Graph
$ Input: n = 3, connections = [[1,2,5],[1,3,6],[2,3,1]]
Output: 6
💡 Note: We need to connect all 3 cities. The minimum spanning tree uses edges [2,3,1] and [1,2,5], giving total cost 1 + 5 = 6.
Example 2 — Impossible to Connect
$ Input: n = 4, connections = [[1,2,3],[3,4,4]]
Output: -1
💡 Note: Cities 1,2 form one component and cities 3,4 form another component. There's no way to connect them since no connection exists between the components.
Example 3 — Single City
$ Input: n = 1, connections = []
Output: 0
💡 Note: Only one city exists, so no connections are needed. The cost is 0.

Constraints

  • 1 ≤ n ≤ 104
  • 0 ≤ connections.length ≤ 104
  • connections[i].length == 3
  • 1 ≤ xi, yi ≤ n
  • xi ≠ yi
  • 0 ≤ costi ≤ 105

Visualization

Tap to expand
Connecting Cities With Minimum Cost123cost=5cost=6cost=112351Available ConnectionsMinimum Spanning TreeMinimum Cost: 6 (edges with cost 1 + 5)Use Kruskal's algorithm to build MST efficiently
Understanding the Visualization
1
Input Cities
n cities and possible connections with costs
2
Build MST
Use Kruskal's algorithm to find minimum spanning tree
3
Output Cost
Return total cost of MST, or -1 if impossible
Key Takeaway
🎯 Key Insight: Use Kruskal's algorithm with Union-Find to greedily build minimum spanning tree
Asked in
Google 42 Amazon 38 Facebook 35 Microsoft 31
67.0K Views
High Frequency
~25 min Avg. Time
956 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen