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 Cost INPUT 1 2 3 5 6 1 n = 3 cities connections = [ [1, 2, 5], [1, 3, 6], [2, 3, 1] ] [city1, city2, cost] ALGORITHM STEPS 1 Sort Edges by Cost [2,3,1], [1,2,5], [1,3,6] 2 Initialize Union-Find Each city is its own set 3 Process Edges Add if no cycle formed 4 Check Connectivity Return total cost or -1 Edge Processing: [2,3,1]: Union(2,3) +1 [1,2,5]: Union(1,2) +5 [1,3,6]: Skip (cycle) -- Total: 1 + 5 = 6 FINAL RESULT 1 2 3 5 1 6 Minimum Spanning Tree OUTPUT 6 OK - All Connected! 2 edges for 3 cities Cost: 5 + 1 = 6 Key Insight: Kruskal's Algorithm builds MST by greedily selecting smallest edges that don't create cycles. Union-Find efficiently detects cycles: if two nodes share a root, adding an edge creates a cycle. Time: O(E log E) for sorting | Space: O(N) for Union-Find | MST needs exactly N-1 edges TutorialsPoint - Connecting Cities With Minimum Cost | Kruskal's Algorithm with Union-Find
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