OpenAI questions

Infection Spread Simulation

OpenAIPhone screenMedium

Simulate an infection spreading on a rectangular grid, day by day. The grid passed in contains only 0 (healthy) and 1 (infected); its 1 cells are infected on day 0.

Neighbors of a cell are the up to 8 cells touching it horizontally, vertically or diagonally. All cells change at the same moment: every decision on a day uses the grid as it stood at the end of the previous day.

simulate(grid, infect_threshold, days) returns the grid after days days.

Part 1: Spreading infection

A healthy cell (0) becomes infected (1) on a day when at least infect_threshold of its neighbors are infected at the end of the previous day. Infected cells stay infected.

  1. Example 1
    days
    2
    grid
    [[0,0,0],[0,1,0],[0,0,0]]
    infect_threshold
    1
    Output
    [[1,1,1],[1,1,1],[1,1,1]]

    Why: With threshold 1, every healthy cell touching the infected center, including diagonally, becomes infected on day 1. Day 2 changes nothing because every cell is already infected.

Constraints

  • 1 <= len(grid) <= 20
  • 1 <= len(grid[0]) <= 20
  • 1 <= infect_threshold <= 8
  • 0 <= days <= 100
  • grid[i][j] is 0 or 1
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question
Infection Spread Simulation: OpenAI interview question | LoopCoach