Wiring the Campsites

MediumgreedyAlso known as Min Cost to Connect All Points

A campground is adding electric hook-ups. Each pitch has map coordinates [x, y]. Cable runs along gravel paths that go only north-south and east-west, so a cable between two pitches costs |x1 - x2| + |y1 - y2| metres.

Power can pass through a pitch, so every pitch just needs some chain of cables to the rest. The manager wants the least total cable.

Your task

Write minCable(pitches). Each entry is [x, y]. A cable between any two pitches costs |x1 - x2| + |y1 - y2|. Return the smallest total cost that connects every pitch to every other, directly or through other pitches.

One pitch needs no cable: return 0. Two pitches can share the same coordinates; joining them costs 0.

minCable(pitches: int[][]) → int

Examples

Example 1
Input
pitches = [[0, 0], [2, 2], [3, 10], [5, 2], [7, 0]]
Output
20
Why

Lay [0,0]–[2,2] (4), [2,2]–[5,2] (3), [5,2]–[7,0] (4) and [2,2]–[3,10] (9). Total 20. The cable to [3,10] is the expensive one, and 9 is the cheapest cable that reaches it: every other one costs at least 10.

Example 2
Input
pitches = [[0, 0], [1, 0], [10, 0], [11, 0]]
Output
11
Why

Two pairs, each with a 1-metre cable. Linking each pitch to its own nearest neighbor gives just those two cables, which leaves two separate groups. One more cable is needed to bridge the gap, and the cheapest is [1,0]–[10,0] at 9. Total 1 + 1 + 9 = 11.

Constraints

  • 1 ≤ pitches.length ≤ 1,000
  • -1,000,000 ≤ x, y ≤ 1,000,000
Start with brute force

List all n(n - 1)/2 possible cables and try every connecting subset of n - 1, keeping the cheapest.

With 20 pitches there are 190 cables and about 6 × 1025 ways to pick 19. Greedy choices are provably safe here, so no search is needed. Kruskal's algorithm (sort all cables, add each that joins two groups) also works, but with 1,000 pitches it must first sort about 500,000 cables.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code