Optimize Water Distribution in a Village - Problem

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, and there could be multiple valid connections between the same two houses with different costs.

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

Input & Output

Example 1 — Basic Water Distribution
$ Input: n = 3, wells = [1,2,1], pipes = [[1,2,1],[2,3,1]]
Output: 3
💡 Note: Build wells in houses 1 and 3 (cost 1+1=2), then connect house 2 to house 3 via pipe (cost 1). Total: 2+1=3.
Example 2 — All Wells Cheaper
$ Input: n = 2, wells = [1,1], pipes = [[1,2,2]]
Output: 2
💡 Note: Building wells in both houses costs 1+1=2, which is cheaper than one well plus pipe (1+2=3).
Example 3 — Pipes More Efficient
$ Input: n = 4, wells = [3,3,3,3], pipes = [[1,2,1],[1,3,1],[1,4,1]]
Output: 6
💡 Note: Build one well in house 1 (cost 3) and connect others via pipes (cost 1+1+1=3). Total: 6.

Constraints

  • 1 ≤ n ≤ 104
  • wells.length == n
  • 0 ≤ wells[i] ≤ 105
  • 1 ≤ pipes.length ≤ 3 × 104
  • pipes[j].length == 3
  • 1 ≤ house1j, house2j ≤ n
  • 0 ≤ costj ≤ 105
  • house1j ≠ house2j

Visualization

Tap to expand
INPUTALGORITHMRESULTH1H2H3$1$2$1$1$1n=3, wells=[1,2,1]pipes=[[1,2,1],[2,3,1]]0Virtual Source1231. Add virtual source2. Sort all edges by cost3. Apply Kruskal MST4. Return total costCost: 3Wells: H1, H3Pipe: H2-H3Optimal solution:Build wells in houses 1,3Connect house 2 via pipeTotal cost: 1+1+1 = 3Key Insight:Transform water distribution into MST by adding virtual source node connectedto all houses with well costs as edge weights. Use Kruskal algorithm for optimal solution.TutorialsPoint - Optimize Water Distribution | MST with Virtual Source
Asked in
Google 45 Amazon 38 Facebook 32 Microsoft 28
78.5K Views
Medium Frequency
~35 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen