Back to Practice Dashboard
Top 150 InterviewEasy

Rotting Oranges

Learn how to solve the 'Rotting Oranges' problem. This detailed resource details brute force and optimized approaches.

Problem Statement

Easy

You are given an m x n grid where each cell can have one of three values:

- 0 representing an empty cell,

- 1 representing a fresh orange, or

- 2 representing a rotten orange.

Every minute, any fresh orange that is 4-directionally adjacent to a rotten orange becomes rotten.

Return the minimum number of minutes that must elapse until no cell has a fresh orange. If this is impossible, return -1.

Write a function orangesRotting(grid: List[List[int]]) -> int.

Constraints
  • m == len(grid)
  • n == len(grid[i])
  • 1 <= m, n <= 10
  • grid[i][j] is 0, 1, or 2

Examples

Example 1
Input
grid = [[2,1,1],[1,1,0],[0,1,1]]
Output
4
Explanation

Minute 0: rotten at (0,0). Fresh at (0,1), (0,2), (1,0), (1,1), (2,1), (2,2). Minute 1: fresh at (0,1) and (1,0) rot. Minute 2: fresh at (0,2) and (1,1) rot. Minute 3: fresh at (2,1) rot. Minute 4: fresh at (2,2) rot.

Example 2
Input
grid = [[2,1,1],[0,1,1],[1,0,1]]
Output
-1
Explanation

The orange in the bottom-left corner (row 2, column 0) is never adjacent to a rotten orange, so it stays fresh.

Need a Hint?
Represent graph node connections as an adjacency list/matrix, then use standard BFS or DFS graph traversal.
Edge Cases to Watch
  • Empty list or null input variables
  • Single item lists/arrays
  • Extremely large input bounds causing integer or stack overflow

Ready to Solve?

Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.

Open in Editor