Python coding

Cheapest cables to connect every site

There are n sites numbered 0 to n - 1 and a list links of cables you could lay, each [a, b, cost]. Pick cables so that every site can reach every other one, directly or through other sites, at the smallest total cost. Return that total, or -1 if even all the cables together leave some site cut off.

Costs are non-negative integers. A pair may appear several times with different costs, and a cable may join a site to itself. n ≥ 1.

Besides the tests, one large input (1,600 sites, 4,799 cables) with a ~200 ms limit (scaled to your device's speed): brute force won't pass.

  • cheapest_network(4, [[0,1,3],[1,2,1],[2,3,4],[0,3,2],[0,2,5]]) → 6
  • cheapest_network(3, [[0,1,2]]) → -1
  • cheapest_network(1, []) → 0
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Greedy works here: sort the cables by cost and consider them cheapest first. Take a cable only if its two sites are not yet connected.

Hint 2

"Already connected?" is the expensive question. Union-find answers it in near-constant time: compare find(a) with find(b), and union the two roots when you take the cable.

Hint 3

Count the groups: start at n and subtract one per cable taken. If it never reaches 1, some site stays cut off: return -1.

Solution and why it works
pythonO(E log E), E = number of cables · O(n + E)
def cheapest_network(n: int, links: list[list[int]]) -> int:
    parent, size = list(range(n)), [1] * n

    def find(x: int) -> int:
        while parent[x] != x:
            parent[x] = parent[parent[x]]        # path halving
            x = parent[x]
        return x

    total, groups = 0, n
    for a, b, cost in sorted(links, key=lambda link: link[2]):    # cheapest cable first
        ra, rb = find(a), find(b)
        if ra == rb:
            continue                             # already connected: this cable would close a loop
        if size[ra] < size[rb]:
            ra, rb = rb, ra
        parent[rb] = ra                          # smaller tree under the larger root
        size[ra] += size[rb]
        total += cost
        groups -= 1
        if groups == 1:
            break                                # n - 1 cables chosen: every site is connected
    return total if groups == 1 else -1

This is Kruskal's algorithm for a minimum spanning tree: the cheapest cable that joins two separate groups is always safe to take, so scanning cables by cost and keeping only those that merge groups gives the cheapest network. Union-find makes "already connected?" near-constant; checking it with a DFS over the chosen cables costs O(n) per cable instead. Stop once one group remains, and return -1 if it never does: cables alone don't prove every site is reachable.