Compute time for virus to infect grid
Company: Uber
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Quick Answer: This question evaluates a candidate's ability to reason about grid-based state propagation, algorithmic problem solving, and performance considerations when managing multi-step updates across a 2D matrix.
Constraints
- 1 <= m, n <= 200
- grid[i][j] is one of {0, 1, 2}
Examples
Input: ([[2,1,1],[1,1,0],[0,1,1]],)
Expected Output: 4
Explanation: The infection spreads outward from the top-left cell. The last healthy individual becomes infected after 4 minutes.
Input: ([[2,1,1],[0,1,1],[1,0,1]],)
Expected Output: -1
Explanation: The healthy individual at the bottom-left is separated by empty cells and can never be infected.
Input: ([[0,2],[0,0]],)
Expected Output: 0
Explanation: There are no healthy individuals initially, so no time is needed.
Input: ([[1]],)
Expected Output: -1
Explanation: There is one healthy individual but no infected individual to start the spread.
Input: ([[2,1,1],[1,1,1],[1,1,2]],)
Expected Output: 2
Explanation: The infection spreads simultaneously from both infected corners, so all healthy individuals are infected in 2 minutes.
Input: ([[2,1,1,1,1]],)
Expected Output: 4
Explanation: In a single row, the infection moves one cell to the right each minute.
Hints
- All initially infected individuals should start spreading the infection at the same time.
- Think of each minute as one level of a breadth-first search starting from all infected cells.