Minimize deaths in spreading plant infection
Company: OpenAI
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
You are given an `m x n` grid representing a garden:
- `0`: empty cell
- `1`: healthy plant
- `2`: infected plant
The garden evolves day by day in the following order:
1. At the start of the day, you may optionally perform one intervention: burn exactly one entire row or one entire column. Every plant in that line is removed immediately. Burned cells become empty forever.
2. Each infected plant spreads the infection to its orthogonally adjacent healthy neighbors.
3. After the spread, check each infected plant. If an infected plant has ever had at least `K` orthogonally adjacent infected neighbors at the end of a day, it becomes marked for death.
4. A marked plant dies exactly `D` days after the first day it was marked, and the cell becomes empty.
Assume that once a plant is marked, its death timer does not reset. Dead or burned cells do not spread infection, cannot be infected again, and are not counted as infected neighbors.
Answer both parts:
1. Given the initial grid, `K`, and `D`, compute how many plants eventually die because of the overcrowding rule.
2. You may use the burn intervention at most once, on any chosen day. Burned plants are not counted as deaths. Design an algorithm to choose the best day and the best row or column to burn so that the number of eventual deaths is minimized.
Quick Answer: This question evaluates a candidate's ability to model and simulate dynamic grid processes, reason about infection propagation and delayed state changes, and incorporate constrained intervention decisions.
Part 1: Count overcrowding deaths in an infected garden
You are given an `m x n` grid representing a garden:
- `0` = empty cell
- `1` = healthy plant
- `2` = infected plant
The garden evolves day by day with no burning in this part:
1. Every infected plant spreads infection to its orthogonally adjacent healthy neighbors.
2. After the spread, each infected plant is checked. If it has at least `K` orthogonally adjacent infected neighbors at the end of that day, it becomes marked for death.
3. A marked plant dies exactly `D` days after the first day it was marked, and its cell becomes empty.
Important rules:
- Once a plant is marked, its death timer never resets.
- A marked plant is still infected and still spreads infection until the day it dies.
- Dead plants become empty forever and cannot spread or be infected again.
- Newly infected plants can also be marked on the same day they were infected.
Return the total number of plants that eventually die because of the overcrowding rule.
Constraints
- `grid[i][j]` is one of `0`, `1`, or `2`
- `1 <= m, n <= 50`