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 [].
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.
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.
1 <= n <= 100000 <= cables.length <= 500001 <= cost <= 10^5Run 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).
I'm here to help with #473 Which Cables to Lay. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.