MediumUnion FindGraphMinimum Spanning TreeHeap (Priority Queue)Sorting

Connecting Cities With Minimum Cost

LeetCode
1 approach, code in all languages

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
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

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

August 15 · 0d left
Enroll Now