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 0 is 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 []), return 0.
  • 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:

  1. Spread: For every healthy . cell, count how many of its 4 neighbors were infected at the end of day k - 1. Healthy cells with at least threshold infected neighbors become infected on day k.
  2. Recovery: Cells infected on day k - d (initial I sources count as infected on day 0) recover today and turn into R. R cells are permanently immune: they do not transmit infection and cannot be reinfected.
  3. Newly infected cells on day k can only infect others starting on day k + 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 threshold rule are identical to Part 3; v cells can be infected and transmit infection during their contagious window just like . cells.
  • Once a cell has been infected for d full days: cells that were originally v recover to R, while all other infected cells (originally . or initial I) die and become X.
  • X cells do not transmit infection and cannot be reinfected.
  • Return (day_last_infection_ends, death_count, final_grid). Any . or v cell 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 d days" 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

  1. 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 initial I source 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 0
    

    Expanding outward from multiple starting points one layer per step is called multi-source Breadth-First Search (BFS): we place every initial I into a single first-in, first-out (FIFO) queue as Day 0, and each BFS layer corresponds to one full day passing.

  2. 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_neighbors helper 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 neighbors
    
  3. Part 1 · Load all initial sources into the queue at day 0

    Before spreading anything, scan the grid once:

    • Every I cell enters queue immediately and is recorded in infected_day with day 0.
    • Every . cell increments healthy_remaining, so at the end we can tell in O(1) time whether any healthy cell was left unreachable.

    Notice that infected_day does double duty: it stores the day number and acts as our visited set (any cell in infected_day has 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
    
  4. Part 1 · Expand layer by layer and handle unreachable cells

    Pop one infected cell (r, c) from the front of queue and inspect its four neighbors. Whenever a neighbor is . and not yet in infected_day, it catches the infection on infected_day[(r, c)] + 1. Why is the very first visit guaranteed to be the earliest possible day? Because a FIFO queue processes all Day 0 cells before any Day 1 cell, all Day 1 cells before any Day 2 cell, 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 = 0
    

    Finally, guard against an empty grid [] at the top, and return -1 if healthy_remaining > 0 after 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.

  5. Part 2 · Immune walls `#`: verify why zero code changes are needed

    Now # cells can appear in the grid as permanently immune walls. Trace what our days_to_infect_all function 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
    
    1. In the BFS loop, we only enqueue neighbors with grid[nr][nc] == ".", so # never enters the queue and never spreads infection.
    2. In the initial scan, healthy_remaining only counts ., so # is not required to become infected.
    3. Any . completely sealed off behind # walls is never reached, leaving healthy_remaining > 0 and returning -1.

    In an interview, explicitly walking through these three points shows deliberate verification rather than luck.

    ✅ Submit now — Part 2 tests should pass.

  6. Part 3 · Why BFS is no longer enough: switch to day-by-day simulation

    Part 3 introduces two rules that break shortest-path BFS:

    1. An infected cell is only contagious for d days, after which it recovers to R.
    2. A healthy cell needs at least threshold neighbors 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_infected that 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_infected and stage results in newly_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 day t is still contagious during the spread step of day t + d, and only turns into R at the end of day t + d.

  7. Part 3 · Implement `simulate_recovery` and trace an example

    Strings in Python are immutable, so we first copy grid into cells, a 2D list of characters. When removing recovered cells in Step 2, we iterate over list(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_grid
    

    Notice what happens when there are no initial I cells: active_infected starts empty, the while loop runs zero times, and (0, original_grid) is returned automatically.

    ✅ Submit now — Part 3 tests should pass.

  8. 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:

    1. Vaccinated v cells can also catch the infection, so in Step 1 we check if cells[r][c] not in (HEALTHY, VACCINATED): continue.
    2. In Step 2, when an infection finishes its d days, a cell that started as v recovers to R, whereas any other infected cell (originally . or initial I) dies and becomes X.

    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 input grid, so checking grid[r][c] != VACCINATED tells 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 both simulate_recovery and simulate_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.

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 the N cells once to initialize the queue, and each cell is pushed into and popped from the FIFO queue at most once because infected_day prevents revisits; each pop inspects at most 4 neighbors (O(1) work).
    • Space: O(N). Both the queue and the infected_day dictionary store at most N cell coordinates.
  • Parts 3–4 (simulate_recovery and simulate_with_death):
    • Time: O((T + 1) * N). Reading the initial grid takes O(N) even when T = 0, and each of the T simulated days scans all N cells, checking up to 4 neighbors per cell in O(1) dictionary lookups.
    • Space: O(N). The mutable 2D character copy cells, the active_infected dictionary, and the daily newly_infected list each hold at most N entries.

Edge cases

  • Empty grid [] (or [""]): days_to_infect_all returns 0 because zero healthy . cells remain; simulate_recovery returns (0, []).
  • No initial I sources: If . cells exist, days_to_infect_all returns -1 because healthy_remaining > 0; simulate_recovery and simulate_with_death skip the while loop and return Day 0 with the original grid (and 0 deaths).
  • Only I and # cells: healthy_remaining starts at 0, so days_to_infect_all returns 0 immediately.
  • threshold > 4: Since every cell has at most 4 orthogonal neighbors, no new cell can ever reach the threshold; initial I cells simply finish their d days on Day d and stop.
  • Initial I cells in Part 4: Initial I cells were not marked v, so they count as unvaccinated and turn into X after d days.
  • Untouched v and . cells in Part 4: Cells that never catch the infection remain v or . 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 collect newly_infected first and write them in Step 3.
  • Recovering cells before counting spread on day start_day + d: A cell infected on Day 0 with d = 1 must infect its neighbors on Day 1 and then turn into R at the end of Day 1. Swapping Step 1 and Step 2 prevents d = 1 infections from ever spreading.
  • Checking cells[r][c] == "v" instead of grid[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 input grid to see whether that cell started as "v".
  • Deleting keys from active_infected while iterating over it directly: Writing for pos, start in active_infected.items(): del active_infected[pos] raises RuntimeError: dictionary changed size during iteration in Python. Wrap it in list(active_infected.items()).
  • Trying to compute Part 3 as days_to_infect_all(grid) + d: That shortcut only happens to work when threshold == 1; for threshold >= 2, finite contagiousness d changes which cells can ever be infected at all.

Follow-up questions

  • What if infection also spreads diagonally (8 directions)? Replace the 4 tuples in DIRS with all 8 horizontal, vertical, and diagonal offsets; none of the BFS or simulation logic needs to change.
  • What if the grid is huge (10^6 cells) and very few cells ever get infected? Instead of scanning all N cells every day, iterate only over the cells currently in active_infected and tally neighbor counts in a temporary dictionary neighbor_counts[(nr, nc)] += 1 for healthy/vaccinated neighbors. Since each cell is infected at most once and stays in active_infected for d days, the total neighbor-checking work across the entire outbreak drops from O(T * N) to O(N + I_total * d), where I_total <= N is the total number of cells that ever catch the infection.
  • What if recovered R cells lose immunity after m days and turn back into .? Now cells can be re-infected, so the simulation might loop forever instead of terminating. You would track recovered_on[(r, c)] = today to revert R -> . after m days, and detect infinite cycles either with a max_days cap or by hashing the full state (grid + remaining timers) into a seen set.
  • 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