Optimize Water Distribution in a Village, explained

Optimize Water Distribution in a Village becomes an ordinary minimum spanning tree problem once you add one imaginary node, a reservoir, and treat drilling a well at a house as laying a pipe from that reservoir to the house. Run Kruskal's algorithm with union-find on the well edges plus the real pipes, and the total weight of the tree is the answer, in O((n + m) log(n + m)) time.

By Published 9 min read

What the problem asks

A village has n houses, numbered 1 to n. A house gets water in one of two ways: drill a well at that house, at a price that differs per house, or lay a pipe between two houses, at a price per pipe, with water flowing both ways. A house is served if it has a well, or if it is linked by pipes, directly or through other houses, to some house that has a well. Return the smallest total amount you must spend so that every house is served. There can be more than one pipe offer for the same pair of houses, at different prices.

Small examples, written for this page
HousesWell prices (house 1, 2, ...)Pipe offers (a, b, price)Cheapest planTotal
3[5, 4, 6](1, 2, 1), (2, 3, 3)Well at house 2, pipes 1-2 and 2-38
2[2, 3](1, 2, 10)Drill both wells; the pipe is too expensive5
4[9, 1, 9, 9](1, 2, 2), (3, 4, 2), (2, 3, 7)Well at 2, pipes 1-2, 3-4 and 2-312
1[7]noneOne house, one well7
Small examples, written for this page. Scroll sideways on a small screen.

Look at the third row. Houses 3 and 4 form a pair joined by a cheap pipe, so they only need one source between them. Their source can be a well (price 9) or the pipe 2-3 (price 7) to a house that already has water. The pipe wins.

Ask first: are all prices positive, and can pipe offers repeat? With positive prices a pipe that closes a loop is never worth buying, which is what makes the tree view work.

A slow approach first

If you knew which houses get wells, the rest would be easier: treat all of those houses as one already-watered group, then connect everything else with the cheapest pipes, which is Kruskal's algorithm on the pipes alone. So the brute force tries every non-empty set of well houses, solves the pipe part for each, and keeps the cheapest plan that reaches every house. There are 2^n − 1 sets, so this only works for a handful of houses. It also exposes the real issue: wells and pipes should not be chosen separately.

def cheapest_water_plan_slow(n, wells, pipes):
    best = None
    ordered = sorted(pipes, key=lambda p: p[2])
    for mask in range(1, 1 << n):
        leader = list(range(n + 1))

        def root(x):
            while leader[x] != x:
                x = leader[x]
            return x

        cost = 0
        for h in range(1, n + 1):
            if mask >> (h - 1) & 1:
                leader[root(h)] = root(0)
                cost += wells[h - 1]
        for a, b, price in ordered:
            ra, rb = root(a), root(b)
            if ra != rb:
                leader[ra] = rb
                cost += price
        if all(root(h) == root(0) for h in range(1, n + 1)):
            best = cost if best is None else min(best, cost)
    return best
Brute force over well sets: O(2^n · m log m).

The main approach: a virtual reservoir and a spanning tree

Invent node 0, an imaginary reservoir that already has water. Drilling a well at house h is then the same as laying a pipe from node 0 to house h, so add an edge (0, h) with the well's price. The question becomes: what is the cheapest set of edges that joins nodes 0 to n into one piece? That is a minimum spanning tree on n + 1 nodes.

Why is it the same problem? Any valid plan links every house to some well, so in the new graph every house reaches node 0 and the plan's edges span the graph. Going the other way, in any spanning tree the edges touching node 0 are wells, the rest are pipes, and each house has a path to a well. Costs match edge for edge, so the cheapest plan and the cheapest spanning tree have the same total.

Kruskal sorts all edges by price and accepts each edge that joins two separate pieces; union-find answers "already connected?" in nearly constant time. With n + 1 nodes, a spanning tree has exactly n edges, so you can stop as soon as you have accepted n of them.

def cheapest_water_plan(n, wells, pipes):
    # Node 0 is an imaginary reservoir; a well at house h is an edge 0-h.
    edges = [(price, 0, h) for h, price in enumerate(wells, start=1)]
    edges += [(price, a, b) for a, b, price in pipes]
    edges.sort()

    leader = list(range(n + 1))

    def find(x):
        while leader[x] != x:
            leader[x] = leader[leader[x]]  # path halving
            x = leader[x]
        return x

    spent = used = 0
    for price, a, b in edges:
        ra, rb = find(a), find(b)
        if ra == rb:
            continue  # this edge would close a loop
        leader[ra] = rb
        spent += price
        used += 1
        if used == n:  # n + 1 nodes need exactly n edges
            break
    return spent
Python: Kruskal with a virtual node 0 and path halving.
function cheapestWaterPlan(n, wells, pipes) {
  const edges = wells.map((price, i) => [price, 0, i + 1]);
  for (const [a, b, price] of pipes) edges.push([price, a, b]);
  edges.sort((x, y) => x[0] - y[0]);

  const leader = Array.from({ length: n + 1 }, (_, i) => i);
  const find = (x) => {
    while (leader[x] !== x) {
      leader[x] = leader[leader[x]];
      x = leader[x];
    }
    return x;
  };

  let spent = 0;
  let used = 0;
  for (const [price, a, b] of edges) {
    const ra = find(a);
    const rb = find(b);
    if (ra === rb) continue;
    leader[ra] = rb;
    spent += price;
    used += 1;
    if (used === n) break;
  }
  return spent;
}
JavaScript: the same plan. Sort with a numeric comparator, never the default sort.

Trace the first example. The edges sorted by price are 1-2 (1), 2-3 (3), 0-2 (4), 0-1 (5), 0-3 (6). Kruskal takes the first three, which is n = 3 edges, and stops at a total of 8: one well at house 2 plus two pipes.

Prim's algorithm as an alternative

Prim grows one tree from node 0. Push every well edge into a min-heap, then repeatedly pop the cheapest edge that reaches a house not yet in the tree, add that house, and push its pipes. Same big-O with a binary heap, but it wants an adjacency list. Kruskal is usually shorter to write under time pressure; naming both and saying why you picked one tends to land well.

Complexity

n houses, m pipe offers
ApproachTimeExtra space
Try every set of wellsO(2^n · m log m)O(n + m)
Kruskal with virtual nodeO((n + m) log(n + m)) for the sort, union-find is almost freeO(n + m)
Prim with a binary heapO((n + m) log(n + m))O(n + m)
n houses, m pipe offers. Scroll sideways on a small screen.

Path halving alone keeps the union-find shallow in practice. Adding union by size gives the textbook inverse-Ackermann bound per operation.

Edge cases worth testing

  • One house and no pipes: the answer is that house's well price.
  • Pipes so pricey that drilling everywhere wins, like the second example.
  • Several pipe offers between the same two houses. Sorting handles it; the cheaper one is considered first and the other is rejected as a loop.
  • A house with no pipes at all. It must get its own well, and the virtual edge guarantees the graph stays connected.

This version can never be impossible, because every house has a well edge to node 0. In Connecting Cities With Minimum Cost that safety net is gone and you must report when the cities cannot all be joined.

Common mistakes

  • Picking the cheapest well first and then building a spanning tree on the pipes. That fixes the number of wells at one, and the second example shows two wells can be cheaper.
  • Using the default JavaScript sort, which compares as strings, so a price of 10 sorts before 9.
  • Forgetting to offset house numbers by one when building the well edges.
  • Stopping after n − 1 edges as if there were n nodes. With the reservoir there are n + 1 nodes and the tree needs n edges.
  • Not explaining why the reduction is valid. Interviewers usually want the two-way argument: every plan is a spanning tree and every spanning tree is a plan.

Saying it out loud

Fictional example

How a candidate might pitch the idea in under a minute
Candidate
Choosing wells and pipes separately gets messy, because a well is just another way to bring water in. So I'll add a node 0 that stands for the water source, and a well at house h becomes an edge from 0 to h with the well's price.
Candidate
Now every valid plan connects all n + 1 nodes, and every spanning tree is a valid plan, so I need a minimum spanning tree. I'll use Kruskal: sort all edges, union-find to skip loops, stop at n edges.
Candidate
Sorting dominates, so it's O(E log E) with E = n + m, and O(n + m) memory for the edges and parent array.

Where this pattern shows up next

The virtual node idea is worth remembering on its own: whenever a node can be "bought" outright instead of connected, a fake source node turns that purchase into an edge. The plain spanning tree version is Connecting Cities With Minimum Cost. For a change of pace in the same batch, Matrix Chain Multiplication is a cost-minimization problem solved with interval dynamic programming rather than a greedy tree. The broader topic list is on the algorithm interview questions page.

Practicing with Natively

When you rehearse graph questions, Natively can read a problem statement from a screenshot and suggest which pattern fits, so you can compare its hint with your own plan after a real attempt. It can also transcribe a mock session on your computer, which makes it easy to check whether you justified the virtual node and stated the complexity clearly. See how an AI interview assistant fits into a practice routine.

Questions people ask

How do you solve Optimize Water Distribution in a Village?

Add an imaginary node 0 and treat each well as an edge from node 0 to its house, priced at the well cost. Then build a minimum spanning tree over nodes 0 to n with Kruskal or Prim; its total weight is the cheapest plan.

Why does adding a virtual node work?

Every valid plan connects each house to some well, which means connecting it to node 0, so the plan spans the graph. Every spanning tree is also a valid plan: edges touching node 0 are wells and the rest are pipes.

What is the time complexity?

With n houses and m pipes there are n + m edges. Sorting them costs O((n + m) log(n + m)), and the union-find work is close to linear, so sorting dominates. Extra space is O(n + m).

Should I use Kruskal or Prim for this problem?

Either is accepted. Kruskal with a sorted edge list and union-find is usually quicker to write; Prim with a heap suits adjacency lists. Say which one you chose and why.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP