← Questions

Time for a virus to infect the whole grid

0
UberCodingLast asked Feb 2026

A coding interview question asked in Uber's technical phone screen, last asked Feb 2026. It tests bfs, grids and simulation.

A grid has infected, healthy and empty cells. Every minute, each infected cell infects its healthy neighbours up, down, left and right, all at the same time. Return the number of minutes until no healthy cell is left, or -1 if some healthy cell can never be reached.

Interface

Unless you agree on a different interface with the interviewer, assume:

  • minutes_to_infect(grid: list[list[int]]) -> int — 0 is empty, 1 is healthy, 2 is infected. If no healthy cell exists at the start, return 0.

Example

minutes_to_infect([[2, 1, 1],
                   [1, 1, 0],
                   [0, 1, 1]])  ->  4

minutes_to_infect([[2, 1, 1],
                   [0, 1, 1],
                   [1, 0, 1]])  ->  -1    # the bottom-left cell is cut off

minutes_to_infect([[0, 2]])     ->  0

Constraints

  • 1 <= rows, cols <= 1000.

Clarifying questions

  • Do several infected cells start at once?
  • Does infection spread diagonally?
  • Can empty cells block the spread? (Yes, they are walls.)
  • Should the input grid be left unchanged?

What a strong answer covers

  • The naive simulation: scan the whole grid each minute and infect neighbours, which costs O((rows × cols)²) in the worst case, such as a long snake-shaped path.
  • Multi-source BFS: start with every infected cell in the queue at minute 0, process level by level, and count healthy cells as they are infected. O(rows × cols) time and space.
  • Why updating in place during a scan is wrong (a cell infected this minute would spread in the same minute) unless you track the minute.
  • Checking for leftover healthy cells to return -1.
  • Tests: no healthy cells, no infected cells but some healthy ones, an isolated healthy cell.

Follow-ups

  • Return the minute at which each cell becomes infected.
  • Some cells are immune for the first t minutes.
  • Infection spreads with probability p per neighbour per minute. Estimate the expected time.

Where it's asked

  • Uber · Technical phone screen · Last asked Feb 202660 min · One medium problem with a follow-up, or two short ones; sometimes object-oriented design

What it tests

bfs · grids · simulation

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding