Optimize Water Distribution in a Village - Problem

You are tasked with designing an optimal water distribution system for a village with n houses. To ensure every house has access to water, you have two options for each house:

  1. Build a well directly inside the house at cost wells[i-1] for house i
  2. Connect to another well via pipes with costs specified in the pipes array

The pipes array contains entries [house1, house2, cost] representing the cost to connect two houses bidirectionally. Multiple connections between the same houses are possible with different costs.

Goal: Find the minimum total cost to supply water to all houses in the village.

This is a classic Minimum Spanning Tree problem with a twist - we can add virtual wells!

Input & Output

example_1.py โ€” Basic village with 3 houses
$ Input: n = 3, wells = [1, 2, 2], pipes = [[1, 2, 1], [2, 3, 1]]
โ€บ Output: 3
๐Ÿ’ก Note: Optimal: Build well at house 1 (cost 1), connect house 2 to house 1 via pipe (cost 1), connect house 3 to house 2 via pipe (cost 1). Total cost = 1 + 1 + 1 = 3.
example_2.py โ€” Expensive pipes scenario
$ Input: n = 2, wells = [1, 1], pipes = [[1, 2, 2]]
โ€บ Output: 2
๐Ÿ’ก Note: Building wells in both houses costs 1 + 1 = 2, while connecting via pipe would cost min(1) + 2 = 3. Better to build individual wells.
example_3.py โ€” Large village optimization
$ Input: n = 4, wells = [3, 3, 3, 4], pipes = [[1, 2, 2], [1, 3, 2], [2, 4, 2]]
โ€บ Output: 7
๐Ÿ’ก Note: Build well at house 1 (cost 3), connect houses 2, 3, 4 via minimum cost pipes: 1-2 (cost 2), 1-3 (cost 2). Total = 3 + 2 + 2 = 7.

Time & Space Complexity

Time Complexity
โฑ๏ธ
O((m+n) log(m+n))

Sorting (m+n) edges takes O((m+n) log(m+n)), Union-Find operations are nearly O(1) with path compression

n
2n
โšก Linearithmic
Space Complexity
O(m+n)

Space for storing edges, Union-Find parent array, and rank array

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค n โ‰ค 104
  • wells.length == n
  • 0 โ‰ค pipes.length โ‰ค 3 ร— 104
  • pipes[j].length == 3
  • 1 โ‰ค wells[i] โ‰ค 105
  • 1 โ‰ค pipes[j][0], pipes[j][1] โ‰ค n
  • 0 โ‰ค pipes[j][2] โ‰ค 105
  • pipes[j][0] โ‰  pipes[j][1]
Asked in
25.0K Views
Medium Frequency
~15 min Avg. Time
850 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