Stealth Interview
  • Features
  • Pricing
  • Blog
  • Login
  • Sign up

Leetcode #1168: Optimize Water Distribution in a Village

In this guide, we solve Leetcode #1168 Optimize Water Distribution in a Village in Python and focus on the core idea that makes the solution efficient.

You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Leetcode

Problem Statement

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

Quick Facts

  • Difficulty: Hard
  • Premium: Yes
  • Tags: Union Find, Graph, Minimum Spanning Tree, Heap (Priority Queue)

Intuition

We need to repeatedly access the smallest or largest element as the input changes.

A heap provides fast insertions and removals while keeping order.

Approach

Push candidates into the heap as you scan, and pop when you need the best element.

Keep the heap size bounded if the problem requires a top-k structure.

Steps:

  • Push candidates into a heap.
  • Pop the best candidate when needed.
  • Maintain heap size or invariants.

Example

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.

Python Solution

class Solution: def minCostToSupplyWater( self, n: int, wells: List[int], pipes: List[List[int]] ) -> int: def find(x: int) -> int: if p[x] != x: p[x] = find(p[x]) return p[x] for i, w in enumerate(wells, 1): pipes.append([0, i, w]) pipes.sort(key=lambda x: x[2]) p = list(range(n + 1)) ans = 0 for a, b, c in pipes: pa, pb = find(a), find(b) if pa != pb: p[pa] = pb n -= 1 ans += c if n == 0: return ans

Complexity

The time complexity is O((m+n)×log⁡(m+n))O((m + n) \times \log (m + n))O((m+n)×log(m+n)), and the space complexity is O(m+n)O(m + n)O(m+n). The space complexity is O(m+n)O(m + n)O(m+n).

Edge Cases and Pitfalls

Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.

Summary

This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.


Ace your next coding interview

We're here to help you ace your next coding interview.

Subscribe
Stealth Interview
© 2026 Stealth Interview®Stealth Interview is a registered trademark. All rights reserved.
Product
  • Blog
  • Pricing
Company
  • Terms of Service
  • Privacy Policy