Rotting oranges
Python data engineering interview problem. Difficulty: intermediate. Pattern: Graphs. About 18 minutes. Part of the Pro drill bank.
Count the minutes until every fresh orange in a grid has rotted, or report that some never do. Treat this as a production helper: match the contracted return shape, including empty and duplicate inputs.
A grid models a spread that advances 1 minute at a time from every already-affected cell. Return minutes until no fresh orange remains, using four-directional spread. Return 0 when there is no fresh orange and -1 when some fresh orange is unreachable. Do not mutate the grid. Write rotting_oranges(grid: list[list[int]]) -> int. In [2,1,1,2], both fresh oranges touch rotten ends and are reached in 1 minute, so the answer is 1. The starter file already contains the function name, harness and print lines. Keep them and fill only the function body.
Requirements
- Process all rotten cells at the same minute together.
- Count layers of spread, not individual orange updates.
- Return -1 if fresh cells remain unreachable.
Constraints
- 0 is empty, 1 fresh and 2 rotten.
- Movement is up, down, left and right only, and the input must not change.
Examples
Input: rotting_oranges([[2, 1, 1, 2]]) Output: 1 Both rotten oranges spread at the same time, so the two fresh ones rot after a single minute.
Topics: lakebench, python, grid, multi-source, shortest time.
More Python interview questions · All interview problems · Learn data engineering
Rotting oranges
Interview-style drill: Count the minutes until every fresh orange in a grid has rotted, or report that some never do.
Implement `rotting_oranges(grid: list[list[int]]) -> int`. Each cell is `0` (empty), `1` (fresh orange) or `2` (rotten orange). Every minute, each fresh orange that touches a rotten orange up, down, left or right becomes rotten. Return the number of minutes until no fresh orange is left. Return `0` if there was no fresh orange to begin with, and `-1` if some fresh orange can never rot. The grid must not be modified.