Rotten Oranges

Asked atAmazonInformaticaMeeshoMicrosoftPGPrincipal Global ServicesUber
1Give yourself 5 minutes
2Answer out loud, not in your head
3Then compare with the answer below

The problem

Given an n x m grid, where each cell has the following values :

2 - represents a rotten orange 1 - represents a Fresh orange 0 - represents an Empty Cell Every minute, if a fresh orange is adjacent to a rotten orange in 4-direction ( upward, downwards, right, and left ) it becomes rotten.

Return the minimum number of minutes required such that none of the cells has a Fresh Orange. If it's not possible, return -1.

Input: grid = [ [2, 1, 1] , [0, 1, 1] , [1, 0, 1] ] Output: -1 Explanation: Orange at (3,0) cannot be rotten.

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

Input: grid = [[0,1,2],[0,1,2],[2,1,1]]

  • 1 <= n, m <= 500
  • grid[i][j] == 0 or 1 or 2

cpp

class Solution{
public:
    int orangesRotting(vector<vector<int>> &grid) {
       
    }
};

java

class Solution {
    public int orangesRotting(int[][] grid) {
     
    }
}

python

class Solution:
    def orangesRotting(self, grid):

javascript

class Solution {
    orangesRotting(grid) {
      
    }
}

csharp

public class Solution {
    public int OrangesRotting(int[][] grid) {

    }
}

go

func orangesRotting(grid [][]int) int {
	
}
Stuck? Show a way to structure it+
  1. 01Enqueue every initially rotten orange and count all fresh oranges.
  2. 02Run BFS in four directions, infecting each fresh orange at most once.
  3. 03Track the infection time by BFS level or store a timestamp with each queued cell.
  4. 04Return the elapsed time when the fresh count reaches zero; otherwise return -1.

Reference answer

Then expect these follow-ups

  • How would you return the minute at which every reachable orange rots?

    Tests: BFS state design

  • Why is running BFS independently from each rotten orange inefficient?

    Tests: complexity analysis

Free to read · better with Enzo

Practice this out loud with Enzo

Enzo runs it as a mock interview, pushes back with follow-ups, and grades you on the rubric.

Next question