15% off all plans & roadmaps Use code
See plansLeetCode 1168 · Solution & editorial
There are n houses in a village. We want to supply water for all the houses by building wells and laying pipes.
Optimize Water Distribution in a Village is a Graph Traversal Patterns (DFS & BFS) problem, in the Minimum Spanning Tree (Kruskal / Prim / DSU + heap) subpattern. The pattern covers DFS/BFS traversal, topological sort, shortest paths, Union-Find, and MST
Find minimum spanning tree using Kruskal's or Prim's algorithm with Union-Find or heap.
The reference solution runs in O(nlogn) time and O(n) space.
Optimize Water Distribution in a Village has been reported in interviews at Google, Facebook, Yahoo.
The full editorial is part of Pro
It explains the core insight, the complexity analysis and the common mistakes, with a worked solution.
Optimize Water Distribution in a Village is a Graph Traversal Patterns (DFS & BFS) problem, in the Minimum Spanning Tree (Kruskal / Prim / DSU + heap) subpattern. Once the approach above makes sense, write it yourself and then work through the neighbouring problems that reuse it.