Wiring the Campsites
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
pitches = [[0, 0], [2, 2], [3, 10], [5, 2], [7, 0]]
20
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.
pitches = [[0, 0], [1, 0], [10, 0], [11, 0]]
11
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- Hint 1
Look at the second example. If you connect each pitch to its nearest neighbor, is everything connected? What is still missing?
- Hint 2
A cheapest plan uses exactly n - 1 cables and has no loops, since any loop has a cable you could remove and stay connected. So you are choosing a tree.
- Hint 3
Grow the network from one pitch. You always have a connected group and the pitches outside it. Which cable is always safe to add next?
- Hint 4
Use Prim's algorithm. For every outside pitch, keep its cheapest cable into the group. Repeatedly add the outside pitch with the smallest cost, add that cost to the total, then update the other outside pitches with their distance to the new one. With all pairs possible, a plain O(n²) scan is simplest; no heap needed.
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.
How to solve it
The cheapest way to connect everything is a minimum spanning tree. Prim's algorithm grows one group: the cheapest cable leaving the group is always part of some cheapest plan, so take it and repeat.
Trace the first example. Pitches: A [0,0], B [2,2], C [3,10], D [5,2], E [7,0]. Start with A in the group.
- Cheapest cable from A to each outside pitch: B 4, C 13, D 7, E 7. Take B (4). Total 4.
- Update with distances from B: C becomes 9, D becomes 3, E stays 7. Take D (3). Total 7.
- Update with distances from D: C stays 9, E becomes 4. Take E (4). Total 11.
- Update with distances from E: C stays 9 (E to C is 14). Take C (9). Total 20.
Each pitch keeps one number: its cheapest cable into the group so far. When a pitch joins, that number can only go down, and only the new pitch's distances need checking, so one O(n) update per step is enough.
A heap version of Prim's suits sparse graphs. Here every pair can be linked, so the graph is dense and the plain array scan is simpler and faster.
function minCable(pitches) {
const n = pitches.length;
const inTree = new Array(n).fill(false);
const cheapest = new Array(n).fill(Infinity); // best cable into the tree
cheapest[0] = 0;
let total = 0;
for (let added = 0; added < n; added++) {
let pick = -1;
for (let i = 0; i < n; i++) {
if (!inTree[i] && (pick === -1 || cheapest[i] < cheapest[pick])) pick = i;
}
inTree[pick] = true;
total += cheapest[pick];
const [px, py] = pitches[pick];
for (let i = 0; i < n; i++) {
if (inTree[i]) continue;
const d = Math.abs(px - pitches[i][0]) + Math.abs(py - pitches[i][1]);
if (d < cheapest[i]) cheapest[i] = d;
}
}
return total;
}def min_cable(pitches):
n = len(pitches)
in_tree = [False] * n
cheapest = [float('inf')] * n # best cable into the tree
cheapest[0] = 0
total = 0
for _ in range(n):
pick = -1
for i in range(n):
if not in_tree[i] and (pick == -1 or cheapest[i] < cheapest[pick]):
pick = i
in_tree[pick] = True
total += cheapest[pick]
px, py = pitches[pick]
for i in range(n):
if not in_tree[i]:
d = abs(px - pitches[i][0]) + abs(py - pitches[i][1])
if d < cheapest[i]:
cheapest[i] = d
return totalRun your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.