Talentd
FleetCode

1135. Connecting Cities With Minimum Cost

Medium63.5% acceptance1 companyPremium elsewhere, free here

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.

Example 1:

Input: n = 3, connections = [[1,2,5],[1,3,6],[2,3,1]]
Output: 6
Explanation: Choosing any 2 edges will connect all cities so we choose the minimum 2.

Example 2:

Input: n = 4, connections = [[1,2,3],[3,4,4]]
Output: -1
Explanation: There is no way to connect all cities even if all edges are used.

Constraints:

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

Asked at 1 company

Hints open one at a time

Hint 1
What if we model the cities as a graph?
Hint 2
Build a graph of cities and find the minimum spanning tree.
Hint 3
You can use a variation of the Kruskal's algorithm for that.
Hint 4
Sort the edges by their cost and use a union-find data structure.
Hint 5
How to check all cities are connected?
Hint 6
At the beginning we have n connected components, each time we connect two components the number of connected components is reduced by one. At the end we should end with only a single component otherwise return -1.
9:42
Still stuck?Read the written solution, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def solve(self):
3 pass
4
Starter codePython 3Spaces: 4
Examples
Input
3
[[1,2,5],[1,3,6],[2,3,1]]
Input
4
[[1,2,3],[3,4,4]]
Your code is saved on this device.Solution