> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Optimize Water Distribution in a Village

> Tested Python solution for LeetCode 1168 with 19 pytest cases. Generate a practice environment with lcpy.

LeetCode 1168, [Hard](/catalog/hard). Topics: [Union Find](/catalog/topics/union-find), [Graph](/catalog/topics/graph), Minimum Spanning Tree, [Heap (Priority Queue)](/catalog/topics/heap-priority-queue). [View on LeetCode](https://leetcode.com/problems/optimize-water-distribution-in-a-village/description/).

Generate this problem as a practice environment: tested reference solution, 19 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 1168   # by problem number
lcpy gen -s optimize_water_distribution_in_a_village   # by problem name
```

## 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] = [house1_j, house2_j, cost_j]` represents the cost to connect `house1_j` and `house2_j` 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*.

### Examples

![Example 1](https://fastly.jsdelivr.net/gh/doocs/leetcode@main/solution/1100-1199/1168.Optimize%20Water%20Distribution%20in%20a%20Village/images/1359_ex1.png)

```
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.
```

```
Input: n = 2, wells = [1,1], pipes = [[1,2,1],[1,2,2]]
Output: 2
Explanation: We can supply water with cost two using one of the three options:
Option 1:
  - Build a well inside house 1 with cost 1.
  - Build a well inside house 2 with cost 1.
The total cost will be 2.
Option 2:
  - Build a well inside house 1 with cost 1.
  - Connect house 2 with house 1 with cost 1.
The total cost will be 2.
Option 3:
  - Build a well inside house 2 with cost 1.
  - Connect house 1 with house 2 with cost 1.
The total cost will be 2.
Note that we can connect houses 1 and 2 with cost 1 or with cost 2 but we will always choose **the cheapest option**.
```

### Constraints

* 2 \<= n \<= 10^4
* wells.length == n
* 0 \<= wells\[i] \<= 10^5
* 1 \<= pipes.length \<= 10^4
* pipes\[j].length == 3
* 1 \<= house1\_j, house2\_j \<= n
* 0 \<= cost\_j \<= 10^5
* house1\_j != house2\_j

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/optimize_water_distribution_in_a_village/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/optimize_water_distribution_in_a_village/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O((m + n) log(m + n)) where m = len(pipes), n = len(wells)
    # Space: O(n + m)
    def min_cost_to_supply_water(self, n: int, wells: list[int], pipes: list[list[int]]) -> int:
        # Virtual well node 0: connecting house i to it costs wells[i - 1].
        edges = [(w, 0, i + 1) for i, w in enumerate(wells)]
        edges += [(c, a, b) for a, b, c in pipes]
        edges.sort()

        parent = list(range(n + 1))

        def find(x: int) -> int:
            while parent[x] != x:
                parent[x] = parent[parent[x]]
                x = parent[x]
            return x

        total = 0
        components = n + 1
        for cost, a, b in edges:
            ra, rb = find(a), find(b)
            if ra == rb:
                continue
            parent[ra] = rb
            total += cost
            components -= 1
            if components == 1:
                break
        return total
```

## Complexity

| Time | Space |
| - | - |
| O((m + n) log(m + n)) where m = len(pipes), n = len(wells) | O(n + m) |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.