Optimize Water Distribution in a Village

Optimize Water Distribution in a Village is a Hard Data Structures and Algorithms interview problem you can solve, run and submit on Thita.ai. It belongs to the Graph Traversal Patterns (DFS & BFS) pattern, in the Minimum Spanning Tree (Kruskal / Prim / DSU + heap) subpattern.

Problem statement

There are n houses in a village. We want to supply water for all the houses by building wells and laying pipes.

For each house i, we can either build a well inside it directly with cost wells[i - 1] (note the -1 due to 0-indexing), or pipe in water from another well to it. The costs to lay pipes between houses are given by the array pipes, where each pipes[j] = [house1j, house2j, costj] represents the cost to connect house1j and house2j together using a pipe. Connections are bidirectional.

Return the minimum total cost to supply water to all houses.

Example 1: Input: n = 3, wells = [1,2,2], pipes = [[1,2,1],[2,3,1]] Output: 3 Explanation: The image shows the costs of connecting houses using pipes.

The best strategy is to build a well in the first house with cost 1 and connect the other houses to it with cost 2 so the total cost is 3.

Constraints: 1 <= n <= 104 wells.length == n 0 <= wells[i] <= 105 1 <= pipes.length <= 104 pipes[j].length == 3 1 <= house1j, house2j <= n 0 <= costj <= 105 house1j != house2j

Topics and companies

Topics: Union Find, Graph.

Reported in interviews at Google, Facebook, Yahoo.

How to practise Optimize Water Distribution in a Village on Thita.ai

Starter code is provided in C#, C++, Go, Java, JavaScript and Python. Your solution runs against 5 test cases for this problem, with the AI coach available for a hint when you are stuck rather than a finished answer. The reference solution runs in O(nlogn) time and O(n) space.

Open Optimize Water Distribution in a Village in the code editor, or read the Optimize Water Distribution in a Village editorial for a worked solution with its approach and complexity analysis.

Where Optimize Water Distribution in a Village sits in the DSA pattern sheet

Problems related to Optimize Water Distribution in a Village

Other problems that use the same Minimum Spanning Tree (Kruskal / Prim / DSU + heap) and Graph Traversal Patterns (DFS & BFS) techniques:

Preparing this workspace.