AlgoInsight

DSA problem

Optimize Water Distribution in a Village

HardMinimum Spanning TreePattern: Minimum Spanning Treetop600AmazonMicrosoftGoogleUberByteDance

There are n houses in a village, labelled from 1 to n. You want to supply water to every house. For each house i, you can either build a well inside it with cost wells[i - 1], or pipe water from another house. The pipe options are given as pipes[j] = [house1, house2, cost] meaning a bidirectional pipe between house1 and house2 costs cost. Return the minimum total cost to supply water to all n houses.

The clever modelling trick is to introduce a virtual node 0 representing an "infinite water source". Every well at house i becomes an edge from node 0 to node i with weight wells[i - 1]. Combined with the original pipes, the problem becomes "find the minimum spanning tree of a graph on n + 1 nodes". Once you see this reformulation, the problem reduces to a standard MST.

After the reduction, Kruskal's algorithm fits perfectly: sort all edges (wells + pipes) by ascending cost, and greedily accept each edge that joins two different components via a Disjoint Set Union (DSU). The MST has exactly n edges because there are n + 1 nodes; every accepted edge either builds a well (connects a house to the virtual source) or lays a pipe between two houses.

The total work is dominated by the sort, giving O((n + p) log (n + p)) time where p = pipes.length, and the DSU contributes O(n) extra space. The result is the sum of accepted edge weights, which equals the minimum cost to water every house.

Examples

Example 1
Input: n = 3, wells = [1,2,2], pipes = [[1,2,1],[2,3,1]]
Output: 3
Explanation: Build a well at house 1 (cost 1), then pipe from house 1 to house 2 (cost 1) and from house 2 to house 3 (cost 1) — total 3. The virtual node 0 connects to house 1 with weight 1; the MST picks (0,1,1), (1,2,1), (2,3,1).
Example 2
Input: n = 2, wells = [1,1], pipes = [[1,2,1]]
Output: 2
Explanation: Cheapest is one well plus one pipe (cost 1 + 1 = 2). Two wells would also cost 2; the MST picks any spanning combination of cost 2.
Example 3
Input: n = 3, wells = [5,5,5], pipes = []
Output: 15
Explanation: No pipes are available, so every house must have its own well: 5 + 5 + 5 = 15.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

minimum-spanning-treegraphkruskalsunion-findmodelling

Browse all DSA problems