Skip to main content
LeetCode 1168, Hard. Topics: Union Find, Graph, Minimum Spanning Tree, Heap (Priority Queue). View on LeetCode. Generate this problem as a practice environment: tested reference solution, 19 parametrized pytest cases, and a playground notebook:

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

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, full suite in test_solution.py:

Complexity

Tags

Last modified on September 7, 2026