progress

~/problems / Graphs / DFS and connected components

Storm outage: neighbourhoods without a generator

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

After a storm, houses 0 .. n-1 are linked by private cables that still work both ways. A house has power if a chain of cables reaches any house with a backup generator. For every connected group with no generator, the utility wants its size.

Write outage_report(n, cables, generators) -> list[int]:

  • cables holds undirected pairs (a, b); repeats and self-loops may appear.
  • generators lists houses with a generator (may repeat or be empty).
  • Return the dark groups' sizes, largest first. A lone house without a generator is a dark group of size 1. All powered: [].
outage_report(8, [(0, 1), (1, 2), (3, 4), (5, 6)], [4])
# [3, 2, 1]
# groups: {0,1,2} dark, {3,4} powered by 4, {5,6} dark, {7} dark
outage_report(3, [(0, 1), (1, 2)], [2])
# []

Up to 10**5 houses and 2 * 10**5 cables. One test is a 50,000-house street, past Python's recursion limit, so use an explicit stack.

⭐ Bonus: a speed test with 100,000 houses earns a star in O(houses + cables).

Show hint

loop over every house; at each unvisited one, flood its group with a stack, counting its size and checking for a generator (a set makes that O(1)).

Topic: DFS and connected components. Iterative DFS / flood fill; count and label components.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc