Optimize Water Distribution in a Village

HardGraphsunion find

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

A village has n houses numbered 1 to n, and every house needs water. There are two ways to supply a house: - dig a well at house i, which costs wells[i - 1], or - connect it with a pipe to another house that has water. pipes[j] = [house1, house2, cost] means the two houses can be joined in either direction for cost. Several pipes may connect the same pair of houses with different costs. Return the minimum total cost to get water to every house.

Examples

Input: n = 3, wells = [1,2,2], pipes = [[1,2,1],[2,3,1]]
Output: 3
Dig a well at house 1 for 1, then pipe 1-2 and 2-3 for 1 each. Total 3.
Input: n = 2, wells = [1,1], pipes = [[1,2,1],[1,2,2]]
Output: 2
Two wells cost 2, and one well plus the cheaper pipe also costs 2.

Constraints

  • 2 <= n <= 10^4
  • `wells.length == n`
  • 0 <= wells[i] <= 10^5
  • 0 <= pipes.length <= 10^4
  • 1 <= house1, house2 <= n, house1 != house2
  • 0 <= cost <= 10^5

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More union find problems