Infection Spread / Cellular Automata
Medium · Coding · 60 min
A 2D grid represents a group of people, with one person per cell. An infection spreads synchronously day by day to the four cardinal neighbors (up, down, left, right). The problem consists of 4 parts with progressively richer rules.
The grid is given as list[str], where each string is one row and all rows have equal length. Cell symbols:
| Symbol | Meaning | Introduced in |
|---|---|---|
. |
Healthy, susceptible to infection | Part 1+ |
I |
Infected (initial infection source) | Part 1+ |
# |
Naturally immune: never gets infected and blocks transmission | Part 2+ |
R |
Recovered after infection ends, permanently immune (appears only in output) | Part 3+ |
v |
Vaccinated healthy person: can be infected, but recovers when the infection ends | Part 4 |
X |
Deceased (appears only in output) | Part 4 |
Part 1: Multi-Source Spread — Days to Infect All
Implement days_to_infect_all(grid) -> int:
- Day
0is the initial state. On each subsequent day, all healthy.cells 4-adjacent to any cell that was infected at the end of the previous day become infected simultaneously. - Infected cells remain infected permanently (there is no recovery in Parts 1–2).
- Return the number of days required until every
.cell is infected. - If there are no
.cells initially (including an empty grid[]), return0. - If any
.cell can never be infected (e.g., there are no infection sources), return-1.
days_to_infect_all(["I...",
"....",
"...I"]) # 2: both sources spread in parallel; each cell takes the nearest source
days_to_infect_all([".."]) # -1: no infection source
Part 2: Permanently Immune Obstacles
The grid may now contain #: it never gets infected and never transmits infection, acting like a wall. days_to_infect_all still applies:
- Only
.cells need to be infected;#cells are excluded. - If any
.cell is completely walled off and unreachable, return-1.
days_to_infect_all(["I#.",
".#.",
"..."]) # 6: must detour around the middle wall
Part 3: Recovery After D Days + Neighbor Threshold
Implement simulate_recovery(grid, d, threshold=1) -> tuple[int, list[str]] (d >= 1, threshold >= 1, and the input grid contains only ., I, and #).
Each day k (k = 1, 2, ...) proceeds in the following order:
- Spread: For every healthy
.cell, count how many of its 4 neighbors were infected at the end of dayk - 1. Healthy cells with at leastthresholdinfected neighbors become infected on dayk. - Recovery: Cells infected on day
k - d(initialIsources count as infected on day0) recover today and turn intoR.Rcells are permanently immune: they do not transmit infection and cannot be reinfected. - Newly infected cells on day
kcan only infect others starting on dayk + 1.
In other words, a cell infected on day t counts as contagious during the spread step on days t + 1, ..., t + d, and becomes R at the end of day t + d.
Stop the simulation on the first day that ends with zero active infected cells, and return (day_number, final_grid). If there are no initial I sources, return (0, grid) (with a copy of the original rows). Healthy . cells that are never infected remain . in the final grid, and # cells remain unchanged.
simulate_recovery(["I..."], d=2) # (5, ["RRRR"])
simulate_recovery(["I.I",
"...",
"I.."], d=1, threshold=2) # (3, ["RRR", "RR.", "R.."])
simulate_recovery(["I.I",
"...",
"I.."], d=3, threshold=2) # (7, ["RRR", "RRR", "RRR"])
The second and third examples illustrate that when threshold=2, a healthy cell needs two simultaneously contagious neighbors; if cells recover too quickly (small d), downstream cells may never reach the threshold.
Part 4: Mortality Without Immunity
In this Part 4 variant, anyone without immunity dies when their infection ends. Input grids may now also contain v (vaccinated individuals).
Implement simulate_with_death(grid, d, threshold=1) -> tuple[int, int, list[str]]:
- The timeline, spread order, and
thresholdrule are identical to Part 3;vcells can be infected and transmit infection during their contagious window just like.cells. - Once a cell has been infected for
dfull days: cells that were originallyvrecover toR, while all other infected cells (originally.or initialI) die and becomeX. Xcells do not transmit infection and cannot be reinfected.- Return
(day_last_infection_ends, death_count, final_grid). Any.orvcell that is never infected stays as-is.
simulate_with_death(["Iv.",
".#v",
"v.."], d=2) # (6, 5, ["XRX", "X#R", "RXX"])
Clarifying Questions to Ask in an Interview
- Is adjacency 4-directional or 8-directional (do diagonals count)?
- Are daily updates synchronous (computed strictly from yesterday's state) rather than updated in-place during traversal?
- What should be returned when some cells are unreachable (
-1,None, or an exception)? What about an empty grid? - How is "recovers after
ddays" indexed — can a cell still infect neighbors on the day it recovers? - What is the stopping condition: all cells infected, zero active infections remaining, or a fixed day horizon?
- How large are the grid dimensions and day count (can we simulate day by day)?
Step-by-step walkthrough
Part 1 · Understand the problem: infection day equals shortest distance
Every day, all currently infected cells spread one step up, down, left, and right at the exact same time. That means the day a healthy
.cell catches the infection is simply the minimum number of grid steps from that cell to whichever initialIsource is closest.Initial grid Day each cell gets infected I . . . 0 1 2 2 . . . . ---> 1 2 2 1 Largest day = 2, so the answer is 2 . . . I 2 2 1 0Expanding outward from multiple starting points one layer per step is called multi-source Breadth-First Search (BFS): we place every initial
Iinto a single first-in, first-out (FIFO) queue as Day0, and each BFS layer corresponds to one full day passing.Part 1 · Write a helper for in-bounds 4-neighbors
Both our BFS in Parts 1–2 and our daily simulation in Parts 3–4 need to check up, down, left, and right neighbors without stepping outside the grid. Writing a small
get_neighborshelper keeps the main functions clean and bug-free.from collections import deque HEALTHY, VACCINATED, INFECTED, IMMUNE = ".", "v", "I", "#" RECOVERED, DEAD = "R", "X" DIRS = ((1, 0), (-1, 0), (0, 1), (0, -1)) def get_neighbors(grid, r: int, c: int) -> list[tuple[int, int]]: """Return all in-bounds 4-directional neighbor coordinates of (r, c).""" rows = len(grid) cols = len(grid[0]) neighbors = [] for dr, dc in DIRS: nr = r + dr nc = c + dc if 0 <= nr < rows and 0 <= nc < cols: neighbors.append((nr, nc)) return neighborsPart 1 · Load all initial sources into the queue at day 0
Before spreading anything, scan the grid once:
- Every
Icell entersqueueimmediately and is recorded ininfected_daywith day0. - Every
.cell incrementshealthy_remaining, so at the end we can tell inO(1)time whether any healthy cell was left unreachable.
Notice that
infected_daydoes double duty: it stores the day number and acts as our visited set (any cell ininfected_dayhas already caught the infection).queue = deque() infected_day = {} # (row, col) -> int day when that cell caught the infection healthy_remaining = 0 for r in range(rows): for c in range(cols): if grid[r][c] == INFECTED: queue.append((r, c)) infected_day[(r, c)] = 0 elif grid[r][c] == HEALTHY: healthy_remaining += 1- Every
Part 1 · Expand layer by layer and handle unreachable cells
Pop one infected cell
(r, c)from the front ofqueueand inspect its four neighbors. Whenever a neighbor is.and not yet ininfected_day, it catches the infection oninfected_day[(r, c)] + 1. Why is the very first visit guaranteed to be the earliest possible day? Because a FIFO queue processes all Day0cells before any Day1cell, all Day1cells before any Day2cell, and so on.Queue order on ["I..", "..."]: Start: queue = [(0,0):d0], healthy_remaining = 5 Pop (0,0) d0 -> infects (1,0):d1, (0,1):d1 | max_day = 1, healthy = 3 Pop (1,0) d1 -> infects (1,1):d2 | max_day = 2, healthy = 2 Pop (0,1) d1 -> infects (0,2):d2 | max_day = 2, healthy = 1 Pop (1,1) d2 -> infects (1,2):d3 | max_day = 3, healthy = 0Finally, guard against an empty grid
[]at the top, and return-1ifhealthy_remaining > 0after the queue empties.def days_to_infect_all(grid: list[str]) -> int: # Empty grid has zero '.' cells, so 0 days are needed. if not grid or not grid[0]: return 0 rows = len(grid) cols = len(grid[0]) queue = deque() infected_day = {} healthy_remaining = 0 for r in range(rows): for c in range(cols): if grid[r][c] == INFECTED: queue.append((r, c)) infected_day[(r, c)] = 0 elif grid[r][c] == HEALTHY: healthy_remaining += 1 max_day = 0 while queue: r, c = queue.popleft() for nr, nc in get_neighbors(grid, r, c): if grid[nr][nc] == HEALTHY and (nr, nc) not in infected_day: next_day = infected_day[(r, c)] + 1 infected_day[(nr, nc)] = next_day if next_day > max_day: max_day = next_day healthy_remaining -= 1 queue.append((nr, nc)) if healthy_remaining > 0: return -1 return max_day✅ Submit now — Part 1 tests should pass.
Part 2 · Immune walls `#`: verify why zero code changes are needed
Now
#cells can appear in the grid as permanently immune walls. Trace what ourdays_to_infect_allfunction already does when it encounters#:Grid: Infection day trace: I # . 0 # 6 . # . --> 1 # 5 Wave detours around the bottom of the '#' wall! . . . 2 3 4 max_day = 6- In the BFS loop, we only enqueue neighbors with
grid[nr][nc] == ".", so#never enters the queue and never spreads infection. - In the initial scan,
healthy_remainingonly counts., so#is not required to become infected. - Any
.completely sealed off behind#walls is never reached, leavinghealthy_remaining > 0and returning-1.
In an interview, explicitly walking through these three points shows deliberate verification rather than luck.
✅ Submit now — Part 2 tests should pass.
- In the BFS loop, we only enqueue neighbors with
Part 3 · Why BFS is no longer enough: switch to day-by-day simulation
Part 3 introduces two rules that break shortest-path BFS:
- An infected cell is only contagious for
ddays, after which it recovers toR. - A healthy cell needs at least
thresholdneighbors to be contagious on the same day.
Whether two neighbors are contagious at the same time depends on both when they caught the infection and whether the earlier one has already recovered. So instead of shortest paths, we simulate one day at a time using a dictionary
active_infectedthat maps(row, col) -> day_infected:Each day `today = 1, 2, ...` while `active_infected` is non-empty: 1. Spread: For every healthy cell, count neighbors in `active_infected` (yesterday's contagious cells). If count >= threshold, add to `newly_infected`. 2. Recover: Any cell in `active_infected` with `today - start_day >= d` is removed from `active_infected` and becomes 'R'. 3. Activate: Every cell in `newly_infected` becomes 'I' and enters `active_infected` with start day = `today` (contagious starting tomorrow).Order inside the loop is critical: - Step 1 must only read yesterday's
active_infectedand stage results innewly_infected. Writing'I'immediately would let a newly infected cell infect its own neighbor on the very same day! - Step 2 must run after Step 1 because a cell infected on daytis still contagious during the spread step of dayt + d, and only turns intoRat the end of dayt + d.- An infected cell is only contagious for
Part 3 · Implement `simulate_recovery` and trace an example
Strings in Python are immutable, so we first copy
gridintocells, a 2D list of characters. When removing recovered cells in Step 2, we iterate overlist(active_infected.items())because Python forbids deleting keys from a dictionary while iterating over it directly.Let's trace
simulate_recovery(["I..."], d=2)before writing the code:Day 0 (initial): I . . . active_infected = {(0,0): 0} Day 1: I I . . (0,1) infected; (0,0) has 1-0 < 2 so stays I Day 2: R I I . (0,2) infected; (0,0) hits 2-0 == 2 -> R Day 3: R R I I (0,3) infected; (0,1) hits 3-1 == 2 -> R Day 4: R R R I nobody new; (0,2) hits 4-2 == 2 -> R Day 5: R R R R nobody new; (0,3) hits 5-3 == 2 -> R -> active empty! Returns: (5, ["RRRR"])def simulate_recovery( grid: list[str], d: int, threshold: int = 1 ) -> tuple[int, list[str]]: if not grid or not grid[0]: return 0, list(grid) rows = len(grid) cols = len(grid[0]) cells = [] for row in grid: cells.append(list(row)) active_infected = {} for r in range(rows): for c in range(cols): if cells[r][c] == INFECTED: active_infected[(r, c)] = 0 today = 0 while active_infected: today += 1 # Step 1 (Spread): Count yesterday's contagious neighbors. newly_infected = [] for r in range(rows): for c in range(cols): if cells[r][c] != HEALTHY: continue contagious_neighbors = 0 for nr, nc in get_neighbors(cells, r, c): if (nr, nc) in active_infected: contagious_neighbors += 1 if contagious_neighbors >= threshold: newly_infected.append((r, c)) # Step 2 (Recover): Cells infected d days ago turn into 'R'. for (r, c), start_day in list(active_infected.items()): if today - start_day >= d: del active_infected[(r, c)] cells[r][c] = RECOVERED # Step 3 (Activate): Today's newly infected cells start spreading tomorrow. for r, c in newly_infected: cells[r][c] = INFECTED active_infected[(r, c)] = today final_grid = [] for row in cells: final_grid.append("".join(row)) return today, final_gridNotice what happens when there are no initial
Icells:active_infectedstarts empty, thewhileloop runs zero times, and(0, original_grid)is returned automatically.✅ Submit now — Part 3 tests should pass.
Part 4 · Add vaccination and death by sharing one `simulate` helper
Part 4 follows the exact same daily timeline as Part 3, with only two differences:
- Vaccinated
vcells can also catch the infection, so in Step 1 we checkif cells[r][c] not in (HEALTHY, VACCINATED): continue. - In Step 2, when an infection finishes its
ddays, a cell that started asvrecovers toR, whereas any other infected cell (originally.or initialI) dies and becomesX.
How do we know whether an infected cell originally started as
v? Once it catches the infection in Step 3,cells[r][c]is overwritten with"I"! Fortunately, we never modified the inputgrid, so checkinggrid[r][c] != VACCINATEDtells us immediately whether the person lacked immunity.Instead of duplicating the loop, we factor out
simulate(grid, d, threshold, with_death)and call it from bothsimulate_recoveryandsimulate_with_death:def simulate( grid: list[str], d: int, threshold: int, with_death: bool ) -> tuple[int, list[str]]: if not grid or not grid[0]: return 0, list(grid) rows = len(grid) cols = len(grid[0]) cells = [] for row in grid: cells.append(list(row)) active_infected = {} for r in range(rows): for c in range(cols): if cells[r][c] == INFECTED: active_infected[(r, c)] = 0 today = 0 while active_infected: today += 1 # Step 1 (Spread): Both '.' and 'v' can catch the infection. newly_infected = [] for r in range(rows): for c in range(cols): if cells[r][c] not in (HEALTHY, VACCINATED): continue contagious_neighbors = 0 for nr, nc in get_neighbors(cells, r, c): if (nr, nc) in active_infected: contagious_neighbors += 1 if contagious_neighbors >= threshold: newly_infected.append((r, c)) # Step 2 (Recovery / Death): Check untouched `grid` to see if cell started as 'v'. for (r, c), start_day in list(active_infected.items()): if today - start_day >= d: del active_infected[(r, c)] if with_death and grid[r][c] != VACCINATED: cells[r][c] = DEAD else: cells[r][c] = RECOVERED # Step 3 (Activate): Today's newly infected cells start spreading tomorrow. for r, c in newly_infected: cells[r][c] = INFECTED active_infected[(r, c)] = today final_grid = [] for row in cells: final_grid.append("".join(row)) return today, final_grid def simulate_recovery( grid: list[str], d: int, threshold: int = 1 ) -> tuple[int, list[str]]: """Part 3: every infected cell recovers to 'R' after d days.""" return simulate(grid, d, threshold, with_death=False) def simulate_with_death( grid: list[str], d: int, threshold: int = 1 ) -> tuple[int, int, list[str]]: """Part 4: vaccinated 'v' cells recover to 'R'; all other infected cells die ('X').""" days, final_grid = simulate(grid, d, threshold, with_death=True) deaths = 0 for row in final_grid: deaths += row.count(DEAD) return days, deaths, final_grid✅ Submit now — all tests should pass.
- Vaccinated
Intuition & how it works
Imagine dropping several pebbles into a calm pond at the exact same moment: ripples expand outward from every pebble at a steady speed of one square per second, and each dry square gets wet as soon as the nearest ripple reaches it. Parts 1 and 2 work just like those ripples, using multi-source Breadth-First Search (BFS) — a graph search that loads all starting I cells into one FIFO queue (a first-in, first-out line where items are processed in arrival order) at Day 0 so the wave advances across the whole grid one day at a time. Parts 3 and 4 turn the grid into a cellular automaton — a turn-based grid simulation where every cell's next state is decided simultaneously from its neighbors' states at the end of the previous turn.
Why do the obvious shortcuts fail? In Parts 1 and 2, running a separate BFS from each I cell wastes huge effort re-scanning the grid O(N^2) times when many cells start infected, whereas putting all I cells into one shared queue visits every cell at most once. In Parts 3 and 4, trying to derive the answer from Part 1 shortest distances fails as soon as threshold >= 2: an early neighbor might recover (R) before a second neighbor catches the infection, leaving the target cell healthy forever. Worse, if you update cells[r][c] = "I" immediately while scanning the grid, that newly infected cell will infect its own neighbor during the same loop pass, causing the disease to teleport multiple steps in a single day.
Let's trace a tiny Part 3 example with grid = ["I.I", "...", "I.."], recovery duration d = 1, and threshold = 2:
Day 0 (start): I . I active_infected = {(0,0):0, (0,2):0, (2,0):0}
. . .
I . .
Day 1: R I R Step 1: (0,1) sees 2 active neighbors {(0,0),(0,2)};
I . . (1,0) sees 2 active neighbors {(0,0),(2,0)}.
R . . Step 2: Day-0 cells finish d=1 day -> turn into 'R'.
Step 3: (0,1) and (1,0) become 'I' (active = {(0,1):1, (1,0):1}).
Day 2: R R R Step 1: (1,1) sees 2 active neighbors {(0,1),(1,0)} -> infected!
R I . Step 2: (0,1) and (1,0) turn into 'R'.
R . . Step 3: (1,1) becomes 'I' (active = {(1,1):2}).
Day 3: R R R Step 1: Remaining '.' cells see at most 1 active neighbor (< 2).
R R . Step 2: (1,1) turns into 'R'. active_infected is now empty -> stop!
R . . Returns (3, ["RRR", "RR.", "R.."]).
Notice that if d = 3 on the exact same grid, the early infections stay contagious long enough to team up with (1, 1) and eventually infect all nine cells by Day 7.
Complexity
Let N = rows * cols be the total number of cells in the grid, and let T be the number of simulated days in Parts 3 and 4.
- Parts 1–2 (
days_to_infect_all):- Time:
O(N). We scan theNcells once to initialize the queue, and each cell is pushed into and popped from the FIFO queue at most once becauseinfected_dayprevents revisits; each pop inspects at most 4 neighbors (O(1)work). - Space:
O(N). Both thequeueand theinfected_daydictionary store at mostNcell coordinates.
- Time:
- Parts 3–4 (
simulate_recoveryandsimulate_with_death):- Time:
O((T + 1) * N). Reading the initial grid takesO(N)even whenT = 0, and each of theTsimulated days scans allNcells, checking up to 4 neighbors per cell inO(1)dictionary lookups. - Space:
O(N). The mutable 2D character copycells, theactive_infecteddictionary, and the dailynewly_infectedlist each hold at mostNentries.
- Time:
Edge cases
- Empty grid
[](or[""]):days_to_infect_allreturns0because zero healthy.cells remain;simulate_recoveryreturns(0, []). - No initial
Isources: If.cells exist,days_to_infect_allreturns-1becausehealthy_remaining > 0;simulate_recoveryandsimulate_with_deathskip thewhileloop and return Day0with the original grid (and0deaths). - Only
Iand#cells:healthy_remainingstarts at0, sodays_to_infect_allreturns0immediately. threshold > 4: Since every cell has at most 4 orthogonal neighbors, no new cell can ever reach the threshold; initialIcells simply finish theirddays on Daydand stop.- Initial
Icells in Part 4: InitialIcells were not markedv, so they count as unvaccinated and turn intoXafterddays. - Untouched
vand.cells in Part 4: Cells that never catch the infection remainvor.in the final grid and are not counted as deaths.
Common mistakes
- Mutating the grid in-place during Step 1: Setting
cells[r][c] = "I"while still scanning the grid lets today's newly infected cell infect its neighbor later in the same loop. Always collectnewly_infectedfirst and write them in Step 3. - Recovering cells before counting spread on day
start_day + d: A cell infected on Day0withd = 1must infect its neighbors on Day1and then turn intoRat the end of Day1. Swapping Step 1 and Step 2 preventsd = 1infections from ever spreading. - Checking
cells[r][c] == "v"instead ofgrid[r][c] == "v"at recovery time: Once a vaccinated cell catches the infection,cells[r][c]becomes"I", erasing the"v". Always check the unmodified inputgridto see whether that cell started as"v". - Deleting keys from
active_infectedwhile iterating over it directly: Writingfor pos, start in active_infected.items(): del active_infected[pos]raisesRuntimeError: dictionary changed size during iterationin Python. Wrap it inlist(active_infected.items()). - Trying to compute Part 3 as
days_to_infect_all(grid) + d: That shortcut only happens to work whenthreshold == 1; forthreshold >= 2, finite contagiousnessdchanges which cells can ever be infected at all.
Follow-up questions
- What if infection also spreads diagonally (8 directions)? Replace the 4 tuples in
DIRSwith all 8 horizontal, vertical, and diagonal offsets; none of the BFS or simulation logic needs to change. - What if the grid is huge (
10^6cells) and very few cells ever get infected? Instead of scanning allNcells every day, iterate only over the cells currently inactive_infectedand tally neighbor counts in a temporary dictionaryneighbor_counts[(nr, nc)] += 1for healthy/vaccinated neighbors. Since each cell is infected at most once and stays inactive_infectedforddays, the total neighbor-checking work across the entire outbreak drops fromO(T * N)toO(N + I_total * d), whereI_total <= Nis the total number of cells that ever catch the infection. - What if recovered
Rcells lose immunity aftermdays and turn back into.? Now cells can be re-infected, so the simulation might loop forever instead of terminating. You would trackrecovered_on[(r, c)] = todayto revertR -> .aftermdays, and detect infinite cycles either with amax_dayscap or by hashing the full state (grid + remaining timers) into aseenset. - What if transmission is probabilistic (each contagious neighbor infects with probability
p)? That is a Monte Carlo simulation — running many randomized trials with a seeded random number generator (random.Random(seed)) to estimate average outbreak duration or expected deaths.
More OpenAI problems
- GPU Credits / GPU Credit 2
- Social Network / Follow Graph
- Poker Simulation
- Classifier with Noisy Annotators
- Durable Key-Value Store Serialization
- NumPy Puzzle: 1-NN Vectorization → Wx+b Network
- Memory Allocator
- Transformer Bug Hunt
- Distributed Machine Cluster Count and Topology
- Autograd / Manual Backprop + Hillis-Steele Scan