Minimum Removals to Contain Grid Blight
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
An agricultural plot is represented as an R x C grid where each cell holds an integer state at t = 0:
0— Healthy crop1— Infected crop2— Dead (cleared or inert soil)
Time advances in discrete steps t = 1, 2, ... under these rules:
- During each step, every currently Infected (
1) cell transmits the blight to all orthogonally adjacent (up, down, left, right) Healthy (0) cells. - Any crop that becomes newly infected on step
tbegins its own infectious window on stept + 1. - Every Infected cell stays infectious for
Ksteps in total and then permanently turns Dead (2). - Dead (
2) cells remain2forever and neither spread nor contract the blight.
Before step 1 starts (at t = 0), you may intervene by clearing any chosen subset of cells — whether currently 0 or 1 — immediately setting their state to 2.
Implement min_interventions(grid: List[List[int]], K: int) -> int to return the smallest number of cells that must be set to 2 at t = 0 so that no cell left in state 0 at t = 0 ever becomes infected during the outbreak.
def min_interventions(grid: List[List[int]], K: int) -> int:
...
Examples
Example 1
Input: grid = [[1, 0, 0],
[0, 0, 2]], K = 3
Output: 1
Clearing the lone infected crop at (0, 0) turns it into 2 before step 1, leaving zero active sources so none of the four healthy cells ever catch the blight.
Example 2
Input: grid = [[1, 0, 1],
[2, 1, 2]], K = 2
Output: 1
Cell (0, 1) is the only healthy crop and borders three infected cells (0, 0), (0, 2), and (1, 1). Clearing (0, 1) alone (1 intervention) acts as a preemptive removal and beats clearing all three infected neighbors (3 interventions).
Example 3
Input: grid = [[0, 1, 0, 2, 1],
[2, 0, 2, 1, 0]], K = 5
Output: 2
Dead cells at (0, 3) and (1, 2) split the plot into two independent zones. On the left, infected (0, 1) borders three healthy crops; on the right, healthy (1, 4) borders two infected crops. Clearing (0, 1) and (1, 4) stops all spread in 2 interventions, whereas clearing only infected cells costs 3 and clearing only healthy cells costs 4.
Constraints
1 <= R, C <= 20(an emptygridhas0conflicts and returns0)grid[r][c]is0,1, or21 <= K <= 10
Step-by-step walkthrough
Restate the rules and goal
Let us pin down the rules before choosing an algorithm:
gridhasRrows andCcolumns (1 <= R, C <= 20), where0= Healthy,1= Infected, and2= Dead.- Clearing a cell at
t = 0sets its value to2before step1starts. We may clear either an Infected cell (eliminating an active source) or a Healthy cell (digging a firebreak so nothing can catch or cross there). - During each step, every currently Infected cell spreads to its orthogonal (
up,down,left,right) Healthy neighbors, and each Infected cell expires into2afterKsteps (1 <= K <= 10). - Goal: find the smallest number of cells to clear at
t = 0so zero cells that remain0att = 0ever catch the blight.
Example 1 (K = 3): Before t = 0 clearance: [ 1 0 0 ] Clear (0, 0) -> [ 2 0 0 ] [ 0 0 2 ] [ 0 0 2 ] Zero Infected cells remain, so none of the four Healthy cells ever become infected -> return 1.Why exhaustive subset simulation times out
A brute-force approach tests subsets of
0cells,1cell,2cells, and so on, simulating the outbreak step by step until a subset prevents all spread.Why is that infeasible at
20 x 20? With400cells, there are2^400subsets — even checking subsets of size10requiresC(400, 10) ≈ 2.6 × 10^19simulations. Exhaustive search works only on tiny3 x 3test grids; to handle20 x 20instantaneously, we need to examine when the first transmission happens.Key insight: step 1 decides everything, so `K` cancels out
Suppose an Infected cell
u(1) borders a Healthy cellv(0) att = 0, and we clear neither cell. BecauseK >= 1,uis guaranteed to be active during step1, souimmediately infectsvon step1!Now look at the converse: suppose we clear enough cells at
t = 0so that no adjacent(Infected, Healthy)pair survives anywhere on the grid.At t = 0 (after clearance): zero Infected (1) cells border any Healthy (0) cell. -> Step 1: zero Healthy cells touch an Infected neighbor, so 0 new infections occur! -> Steps 2..K: active Infected cells only age out as timers reach 0, so still 0 new infections! -> Step K: all surviving initial Infected cells turn Dead (2). Outbreak finished!Therefore, preventing all future spread is 100% equivalent to breaking every orthogonal
(1, 0)neighbor pair att = 0. Notice thatK(1 <= K <= 10) never alters the answer because any unbroken pair already fails on step1.Model conflicts as a bipartite vertex cover
Translate the grid into a conflict graph:
- Nodes: grid cells.
- Conflict edges: connect two orthogonally adjacent cells whenever one is
1(Infected) and the other is0(Healthy). Dead cells (2),(1, 1)pairs, and(0, 0)pairs produce zero edges.
Choosing the fewest nodes so every edge touches at least one chosen node is a minimum vertex cover.
Why can we not simply clear all conflicted Infected cells, or all conflicted Healthy cells? Look at Example 3:
Example 3 (# means Dead = 2): col: 0 1 2 3 4 row 0: 0 1 0 # 1 Left zone: Infected (0, 1) borders 3 Healthy cells row 1: # 0 # 1 0 Right zone: Healthy (1, 4) borders 2 Infected cells - Clear only Infected cells: 1 (left) + 2 (right) = 3 clearances - Clear only Healthy cells: 3 (left) + 1 (right) = 4 clearances - Mix both sides: clear Infected (0, 1) + Healthy (1, 4) = 2 clearances!Every conflict edge joins an Infected cell (
1) to a Healthy cell (0). A graph whose nodes divide into two groups with edges only between the groups (never within the same group) is a bipartite graph.König's theorem: minimum vertex cover = maximum matching
Although minimum vertex cover is NP-hard on arbitrary graphs, König's theorem makes it polynomial on any bipartite graph:
size of a minimum vertex cover = size of a maximum matchingA matching is a set of conflict edges that share no endpoints (disjoint one-to-one
(Infected, Healthy)pairs).- Why
cover >= matchingis clear:Mcompletely disjoint conflict pairs share zero cells, so any valid plan must spend at least1clearance on each pair — at leastMin total. - What König's theorem adds: on a bipartite graph, a valid vertex cover of size
Malways exists, so computing the maximum matching size directly returnsmin_interventions!
- Why
Build the conflict adjacency map
Scan the
R x Cgrid once and map each Infected cell(r, c)to its orthogonally adjacent Healthy cells(nr, nc). Infected cells with no Healthy neighbors cannot cause conflicts and are omitted.from typing import Dict, List, Set, Tuple Cell = Tuple[int, int] DIRECTIONS = ((1, 0), (-1, 0), (0, 1), (0, -1)) def build_edges(grid: List[List[int]]) -> Dict[Cell, List[Cell]]: """Map each Infected cell (1) to its adjacent Healthy cells (0).""" rows = len(grid) cols = len(grid[0]) if rows > 0 else 0 # edges: {(r, c): [(nr, nc), ...]} — Infected cells with zero Healthy neighbors are omitted. edges: Dict[Cell, List[Cell]] = {} for r in range(rows): for c in range(cols): # Only Infected cells (state 1) can initiate spread at step 1; Dead (2) cells act as walls. if grid[r][c] != 1: continue healthy_neighbors: List[Cell] = [] for dr, dc in DIRECTIONS: nr = r + dr nc = c + dc # Bounds check uses 0 <= nr < rows and 0 <= nc < cols to stay inside the R x C grid. if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 0: healthy_neighbors.append((nr, nc)) if healthy_neighbors: edges[(r, c)] = healthy_neighbors return edgesFind the maximum matching via Kuhn's augmenting-path DFS
Maintain
matched_to, a dictionary mapping each claimedhealthycell to theinfectedcell currently paired with it:- For each
infectedcell, inspect itshealthyneighbors one by one. - If
healthyis unclaimed (current_owner is None), pair them immediately (matching_size += 1). - If
healthyis already claimed bycurrent_owner, recursively asktry_augment(current_owner, ...)whethercurrent_ownercan shift to an alternative Healthy neighbor soinfectedcan takehealthy.
That chain of reassignments is an augmenting path. Within a single outer DFS,
seen_healthyprevents revisiting the same Healthy cell so cycles never cause infinite recursion.def try_augment( infected: Cell, edges: Dict[Cell, List[Cell]], matched_to: Dict[Cell, Cell], seen_healthy: Set[Cell], ) -> bool: """Try to pair `infected` with a Healthy neighbor, rearranging existing pairs if needed.""" for healthy in edges[infected]: # Skip Healthy cells already explored during this single DFS attempt to avoid infinite loops. if healthy in seen_healthy: continue seen_healthy.add(healthy) current_owner = matched_to.get(healthy) # Either `healthy` is unmatched, or `current_owner` can recursively move to a different Healthy cell. if current_owner is None or try_augment(current_owner, edges, matched_to, seen_healthy): matched_to[healthy] = infected return True return FalseTrace Kuhn's algorithm on Example 3 (
[[0, 1, 0, 2, 1], [2, 0, 2, 1, 0]]):Edges: (0, 1) -> [(1, 1), (0, 2), (0, 0)] (0, 4) -> [(1, 4)] (1, 3) -> [(1, 4)] 1. Try (0, 1): (1, 1) is free -> matched_to[(1, 1)] = (0, 1) (matching_size = 1) 2. Try (0, 4): (1, 4) is free -> matched_to[(1, 4)] = (0, 4) (matching_size = 2) 3. Try (1, 3): wants (1, 4), currently owned by (0, 4). Ask (0, 4) to move: its only neighbor (1, 4) is in seen_healthy -> False. (1, 3) has no other neighbors -> False (matching_size = 2) Return 2 (matching the optimal 2-cell cover {(0, 1), (1, 4)}).- For each
Complete solution
Combining
min_interventions,build_edges, andtry_augmentyields the full implementation. BecauseR * C <= 400, at most200pairs can exist simultaneously, bounding recursion depth at201.from typing import Dict, List, Set, Tuple Cell = Tuple[int, int] DIRECTIONS = ((1, 0), (-1, 0), (0, 1), (0, -1)) def min_interventions(grid: List[List[int]], K: int) -> int: """Return the fewest plants to remove (set to Dead) at t = 0 so that the infection never reaches a plant that is Healthy at t = 0. """ # Phase 1: Build the bipartite conflict graph between Infected (1) and Healthy (0) neighbors. # Because K >= 1, any unremoved Infected plant infects every unremoved Healthy neighbor at step 1. # If we break all (Infected, Healthy) neighbor pairs at t = 0, zero plants ever catch the infection. # edges: {(r, c): [(nr, nc), ...]} mapping each Infected cell to its adjacent Healthy cells. edges = build_edges(grid) # Phase 2: Find the maximum bipartite matching using Kuhn's augmenting-path algorithm. # By Konig's theorem, minimum vertex cover size == maximum matching size on a bipartite graph. # matched_to: {healthy_cell: infected_cell} storing which Infected cell currently claims each Healthy cell. matched_to: Dict[Cell, Cell] = {} matching_size = 0 for infected in edges: # Use a fresh `seen` set per starting `infected` cell so cells visited in earlier # failed searches can still be used along newly opened alternating paths. seen_healthy: Set[Cell] = set() if try_augment(infected, edges, matched_to, seen_healthy): matching_size += 1 return matching_size def build_edges(grid: List[List[int]]) -> Dict[Cell, List[Cell]]: """Map each Infected cell (1) to its adjacent Healthy cells (0).""" rows = len(grid) cols = len(grid[0]) if rows > 0 else 0 # edges: {(r, c): [(nr, nc), ...]} — Infected cells with zero Healthy neighbors are omitted. edges: Dict[Cell, List[Cell]] = {} for r in range(rows): for c in range(cols): # Only Infected cells (state 1) can initiate spread at step 1; Dead (2) cells act as walls. if grid[r][c] != 1: continue healthy_neighbors: List[Cell] = [] for dr, dc in DIRECTIONS: nr = r + dr nc = c + dc # Bounds check uses 0 <= nr < rows and 0 <= nc < cols to stay inside the R x C grid. if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 0: healthy_neighbors.append((nr, nc)) if healthy_neighbors: edges[(r, c)] = healthy_neighbors return edges def try_augment( infected: Cell, edges: Dict[Cell, List[Cell]], matched_to: Dict[Cell, Cell], seen_healthy: Set[Cell], ) -> bool: """Try to pair `infected` with a Healthy neighbor, rearranging existing pairs if needed.""" for healthy in edges[infected]: # Skip Healthy cells already explored during this single DFS attempt to avoid infinite loops. if healthy in seen_healthy: continue seen_healthy.add(healthy) current_owner = matched_to.get(healthy) # Either `healthy` is unmatched, or `current_owner` can recursively move to a different Healthy cell. if current_owner is None or try_augment(current_owner, edges, matched_to, seen_healthy): matched_to[healthy] = infected return True return False✅ Submit now — all tests should pass.
Intuition & how it works
Picture embers (1 = Infected) sitting beside dry stalks (0 = Healthy) on a field where bare dirt (2 = Dead) cannot burn. Before step 1 starts, you can clear either embers or dry stalks (turning them into dirt 2) so that no remaining dry stalk ever catches fire. Because K >= 1, any uncleared ember stays active during step 1 and immediately ignites every orthogonally adjacent uncleared stalk; conversely, if zero (1, 0) neighbor pairs survive at t = 0, nothing new catches on step 1 or any later step, and the initial embers simply die out after K steps.
Trying all subsets of cells to clear and simulating each outbreak fails rapidly: a 20 x 20 plot has 400 cells (2^400 subsets, with C(400, 10) ≈ 2.6 × 10^19 subsets of size 10 alone). Simple heuristics such as clearing only Infected cells, clearing only Healthy cells, or greedily deleting whichever cell touches the most conflicts also fail whenever the optimal containment mixes clearing Infected hubs in one region and Healthy firebreaks in another.
Instead, add a conflict edge between every orthogonally adjacent (Infected, Healthy) pair. Selecting the fewest nodes so every edge has at least one selected endpoint is a minimum vertex cover (the smallest node set touching every edge). Because every conflict edge links a 1 on one side to a 0 on the other, this conflict graph is a bipartite graph (a graph whose vertices split into two disjoint sets with edges only between the sets). By König's theorem (which states that on any bipartite graph, the minimum vertex cover has the exact same size as the maximum matching), we only need to compute a maximum matching (the largest collection of non-overlapping one-to-one (Infected, Healthy) edges).
Trace Example 3 on grid = [[0, 1, 0, 2, 1], [2, 0, 2, 1, 0]]:
- Left conflict edges connect Infected
(0, 1)to Healthy(0, 0),(0, 2), and(1, 1); right conflict edges connect Infected(0, 4)and(1, 3)to Healthy(1, 4). - Kuhn's algorithm (which pairs left-side nodes one by one using an augmenting path — an alternating chain of swaps that frees up a partner for the incoming node) pairs
(0, 1) -> (1, 1)(size1) and(0, 4) -> (1, 4)(size2). - Next,
(1, 3)asks for(1, 4)(held by(0, 4)), which cannot move anywhere else. Maximum matching size =2(matching the mixed 2-cell clearance{(0, 1), (1, 4)}).
Complexity
Let V = R × C <= 400 be the number of cells in grid and E be the number of orthogonal (Infected, Healthy) conflict pairs (E < 2V on a 4-connected grid).
- Time:
O(V^2)— Buildingedgesinspects each of theVcells and up to4orthogonal neighbors once inO(V)time. Kuhn's algorithm then launches at mostVdepth-first searches (one per Infected cell with conflicts), andseen_healthyguarantees each search visits every Healthy cell and conflict edge at most once (O(V + E) = O(V)work per search), totalingO(V^2)operations. - Space:
O(V)— Storingedges(O(V + E) = O(V)),matched_to(at mostV / 2pairs),seen_healthy(at mostVcells), and the recursion stack (at mostV / 2 + 1 <= 201frames) all grow linearly withV.
Edge cases
- All Healthy, all Infected, or all Dead grids:
edgesis empty because no1touches a0, immediately returning0. - Empty grid
[]: Handled cleanly (cols = 0), returning0. - Dead cells (
2) acting as natural barriers (e.g.,[[1, 2, 0]]): State2blocks orthogonal contact, generating zero edges and returning0. - One Healthy cell surrounded by Infected cells (Example 2): All conflict edges share that single Healthy cell, so maximum matching size is
1. - Varying
K(1 <= K <= 10): EveryK >= 1yields the exact same minimum clearance count because any surviving(1, 0)pair already spreads on step1.
Common mistakes
- Clearing only Infected cells (or only Healthy cells): Taking
min(#conflicted infected, #conflicted healthy)fails on grids like Example 3 (returning3instead of2) whenever one region has an Infected hub and another has a Healthy hub. - Greedy highest-degree removal: Repeatedly clearing the cell with the most remaining conflicts fails on a plus-shaped cluster (a degree-
4Healthy center surrounded by4Infected arms that each touch1outer Healthy tip), spending5clearances instead of clearing the4Infected arms. - Sharing one
seen_healthyset across all outer loop iterations: After an augmenting swap updatesmatched_to, Healthy cells visited in an earlier failed search can become part of a newly opened path; reusingseen_healthymisses valid pairs and undercounts. - Including diagonal neighbors: Blight spreads strictly up, down, left, and right (
4directions, not8).
Alternative approaches
- Minimum cut / maximum flow: Construct a directed flow network with
source -> infected(capacity1),infected -> healthy(capacityinfinity), andhealthy -> sink(capacity1). By the max-flow min-cut theorem, the minimums-tcut equals the minimum vertex cover, and setting source/sink edge capacities tocost[r][c]naturally solves weighted cell-clearance costs. - Hopcroft–Karp bipartite matching: Finds shortest augmenting paths in breadth-first layers before augmenting multiple vertex-disjoint paths per phase in
O(E × sqrt(V))time; overkill forV <= 400, where Kuhn's short DFS finishes in microseconds, but ideal for massive grids.
Follow-up questions
- Suppose you can clear at most one cell per time step while the blight continues spreading, instead of making every intervention at t = 0. How does the problem change? Now both step-by-step timing and
Kmatter: while you clear one cell before step1, every other Infected cell spreads simultaneously, so widely separated outbreaks may be impossible to contain without losing some Healthy crops. This becomes the firefighter problem (a graph-containment problem where one vertex is protected per round to minimize total burned vertices), which is NP-hard even on trees. On small grids, you would search over(grid_state, remaining_timers)states using branch and bound (pruning search branches whose already-infected count exceeds the best containment found so far) with state memoization. - How would you scale your algorithm if the field grew to 1,000 by 1,000 cells? At
V = 10^6andE ≈ 2 × 10^6, Kuhn'sO(V × E)worst case and recursive DFS would time out or hit Python's recursion limit. Switch to an iterative Hopcroft–Karp solver (O(E × sqrt(V))), index only boundary cells (cells adjacent to the opposite state) as compact integers0..B-1in flat arrays, initialize a greedy maximal matching in oneO(E)pass to shrink augmenting work, and solve disconnected boundary components independently in parallel. - How would your strategy adapt if transmission were probabilistic and decayed with distance rather than guaranteed across immediate neighbors? An Infected cell active for
Ksteps directly infects a Healthy cell at distancedwith cumulative probability1 - (1 - p(d))^K(plus multi-hop cascade risk). If zero infection probability is permitted (p(d) > 0forbidden), every threatened pair still links an initial1to an initial0, keeping the conflict graph bipartite so maximum matching remains exact. Under a nonzero risk budget (such as keeping expected new infections<= tau),Kand multi-hop chains matter again, so you would estimate expected spread via Monte Carlo simulation (averaging outcomes over many random trials) and select clearances via greedy marginal-risk reduction or beam search, validating the chosen set on independent holdout rollouts.
Follow-up questions
- Suppose you can clear at most one cell per time step while the blight continues spreading, instead of making every intervention at t = 0. How does the problem change?
- How would you scale your algorithm if the field grew to 1,000 by 1,000 cells?
- How would your strategy adapt if transmission were probabilistic and decayed with distance rather than guaranteed across immediate neighbors?
Similar questions
- Grid Path Scoring with Streak Bonuses
- Sliding-Window Chat Activity Aggregator
- Jetpack Compose Feedback Rating Widget
- Streaming Prompt Input State Machine
- Minimum-Cost Daily Shirt Schedule Without Adjacent Repeats
- Minimum-Cost Paint Booth Assignment Without Adjacent Repeats
- Cellular Outbreak with Recovery and Mortality
More OpenAI interview questions
- Technical Project Deep Dive and Architecture Trade-Off Defense Medium
- Point-in-Time Credit Ledger with Expiring Grants Medium
- Design a Fault-Tolerant Merchant Payment and Refund Platform Hard Pro
- Why OpenAI? Medium Pro
- Snapshot-Queryable Follow Graph Hard Pro
- Design a Stateless Token-Streaming LLM Inference Service Hard Pro
- Design a Real-Time Multiplayer Chess Service Hard Pro
- Cluster Tree Topology Summary Medium Pro
- Design a Fault-Tolerant Asynchronous Video-Generation Service Hard Pro
- Grid Load-Curtailment Control Plane Hard Pro