MediumUnion FindGraphMinimum Spanning TreeHeap (Priority Queue)Sorting

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^4
  • 1 <= connections.length <= 10^4
  • connections[i].length == 3
  • 1 <= xi, yi <= n
  • xi != yi
  • 0 <= costi <= 10^5

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