Skip to the code
cf.
+25 XP

#473 Which Cables to Lay

medium

A network planner proposes cables[i] = [a, b, cost] between n sites numbered 0 to n - 1. The installer follows a fixed rule: consider the cables from cheapest to most expensive, and among cables with the same cost, the one listed earlier first. A cable is laid if its two sites aren't already connected by cables laid so far.

Write cablesToLay(n, cables) that returns the indexes of the cables that get laid, sorted ascending. If the laid cables don't connect every site, return [].

Example 1

Input: n = 4, cables = [[0,1,1],[1,2,2],[0,2,4],[2,3,3],[1,3,5]]
Output: [0,1,3]

Costs 1, 2, and 3 are laid in that order and connect all four sites. Cables 2 and 4 would close loops.

Example 2

Input: n = 3, cables = [[0,1,1],[1,2,1],[0,2,1]]
Output: [0,1]

All three cost the same, so the earlier cables 0 and 1 go first, and cable 2 would close a loop.

Constraints

  • 1 <= n <= 10000
  • 0 <= cables.length <= 50000
  • 1 <= cost <= 10^5
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).