Cheapest Way to Power Every Village With Generators or Lines

Last updated: November 29, 2026

Quick Overview

There are n villages. Building a generator in village i costs gen[i], and a power line between villages a and b costs a given amount. A village has power if it has a generator or is connected by lines to one that does. Return the minimum total cost to power every village.

Google
Coding & Algorithms
Software Engineer
Google
November 29, 2026
Software Engineer
Onsite
Coding & Algorithms
Hard

0

0

0 solved


There are n villages. Building a generator in village i costs gen[i], and a power line between villages a and b costs a given amount. A village has power if it has a generator or is connected by lines to one that does. Return the minimum total cost to power every village.

This Google onsite question hides a minimum spanning tree behind a choice between two kinds of spending. Framed around powering remote sites for Google's connectivity projects, the interviewer is checking for the virtual source node trick, which turns generator costs into ordinary edges so Kruskal solves it directly.

What the Interviewer Expects
  • Adds a virtual source node 0
  • Models each generator as an edge from node 0 to the village
  • Runs Kruskal over the combined edge set
  • Stops after n accepted edges for n + 1 nodes
  • Argues why every optimal plan is a spanning tree of the augmented graph
Key Topics to Cover
Union-Find
Minimum Spanning Tree
Virtual Nodes
Kruskal
Graph Modeling
How to Approach This
  1. Clarify input constraints and edge cases before writing code.
  2. Walk through your approach verbally and confirm with the interviewer before coding.
  3. Start with a brute force solution, then optimize. Mention time and space complexity.
  4. Test your solution with examples, including edge cases like empty input or duplicates.
  5. Consider common patterns: sliding window, two pointers, hash map, BFS/DFS, dynamic programming.
Possible Follow-up Questions
  • Some villages already have generators. How do you incorporate that?
  • Lines have capacity limits on how many villages a generator can serve. Does MST still work?
  • Return the plan: which generators and which lines to build.
Sharpen Your Skills on Codemia

Practice similar problems with our interactive workspace, get AI feedback, and track your progress.

Practice DSA Problems
Sample Answer
Requirements
  • Input: n, list gen of generator costs (index i - 1 for village i), list of (a, b, cost) lines over villages 1..n.
  • Output: minimum total cost so every village has power.
  • Costs are non-neg...
High-Level Design

Add a virtual node 0 standing for an external power source. A generator in village i is exactly an edge (0, i) with cost gen[i]. Now a valid plan is a connected subgraph containing node 0 and ever...


Submit Your Answer
Markdown supported