Taro Logo

Rotting Oranges

Medium
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+33
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
1.8K views
Topics:
ArraysGraphs

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.

Example 1:

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

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 rotten, because rotting only happens 4-directionally.

Example 3:

Input: grid = [[0,2]]
Output: 0
Explanation: Since there are already no fresh oranges at minute 0, the answer is just 0.

Constraints:

  • m == grid.length
  • n == grid[i].length
  • 1 <= m, n <= 10
  • grid[i][j] is 0, 1, or 2.

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What do the integer values in the grid specifically represent for empty cells, fresh oranges, and rotten oranges?
  2. What should be returned if the grid initially contains no fresh oranges at all?
  3. Can we modify the input grid in-place to track the state changes, or should we use additional memory to keep the original grid intact?
  4. What are the minimum and maximum dimensions ($m$ and $n$) of the grid?
  5. Is it possible for the grid to be completely empty or have invalid dimensions?

Brute Force Solution

Approach

Imagine a grid of fruits where some are fresh and some are already spoiled, and every minute the spoilage spreads to touching neighbors. The brute force approach simulates this minute-by-minute process over and over, trying every possible timeline to see how long it takes for everything to spoil.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the entire grid of fruits to see which ones are spoiled.
  2. Simulate the passage of one minute by letting every spoiled fruit contaminate its immediate neighbors that are still fresh.
  3. Repeat this simulation step by step, keeping track of how many minutes have passed.
  4. Stop the simulation once no more fresh fruits can be contaminated.
  5. Check the grid to see if any fresh fruits managed to escape spoilage completely.
  6. If any fresh fruits remain untouched, note that it is impossible to spoil them all.
  7. If all fruits are successfully spoiled, record the total number of minutes it took.
  8. Since you can try different starting assumptions or simply replay the timeline, compare your results to find the absolute minimum time required, or repeat this entire exploration process for every possible starting condition if needed until you find the shortest overall path.

Code Implementation

def oranges_rotting(grid):    row_count = len(grid)    column_count = len(grid[0])    total_minutes = 0    # We must continuously simulate minute-by-minute spoilage until no more changes occur in the grid    while True:        grid_changed = False        next_state_grid = [row[:] for row in grid]        for current_row in range(row_count):            for current_col in range(column_count):                if grid[current_row][current_col] == 2:                    neighbor_offsets = [(-1, 0), (1, 0), (0, -1), (0, 1)]                    for row_offset, col_offset in neighbor_offsets:                        neighbor_row = current_row + row_offset                        neighbor_col = current_col + col_offset                        if 0 <= neighbor_row < row_count and 0 <= neighbor_col < column_count:                            if grid[neighbor_row][neighbor_col] == 1:                                next_state_grid[neighbor_row][neighbor_col] = 2                                grid_changed = True        if not grid_changed:            break        grid = next_state_grid        total_minutes += 1    # We verify if any fresh oranges survived the simulation, meaning complete spoilage was impossible    for current_row in range(row_count):        for current_col in range(column_count):            if grid[current_row][current_col] == 1:                return -1    return total_minutes

Big(O) Analysis

Time Complexity
O(R * C * (R * C)) – To determine the time complexity, let R and C be the number of rows and columns in the grid, where the total number of cells is n = R * C. The brute force approach repeatedly simulates the minute-by-minute spoilage process across the entire grid for multiple possible timelines or starting conditions. In the worst-case scenario, the simulation step visits all n cells repeatedly for up to n minutes as spoilage spreads step by step. This leads to approximately n * n operations, which simplifies to O(n squared) time complexity relative to the total number of cells.
Space Complexity
O(N) – Let N represent the total number of cells in the grid. The auxiliary space is dominated by a queue used for the breadth-first search simulation to track rotting oranges level by level. In the worst-case scenario, nearly all cells in the grid could be fresh and eventually queued, meaning the queue grows proportionally to the input size N. Additionally, a constant amount of extra memory is used for tracking variables like minute counters and grid dimensions, keeping the overall auxiliary memory bounded linearly.

Optimal Solution

Approach

Instead of checking everything separately, we can think of this like a spreading disease that moves outward in simultaneous waves from all currently rotten fruit. By tracking how many minutes it takes for the rot to reach the farthest fresh fruit, we can efficiently find the total time needed.

Here's how the algorithm would work step-by-step:

  1. Scan the entire grid to find all the currently rotten fruit and keep track of how many fresh pieces still exist.
  2. Gather all the rotten pieces into a starting group because they will all begin spreading the rot at the exact same time.
  3. Set a timer to zero to keep track of how many minutes have passed.
  4. Look at all the immediate neighbors of the currently rotten pieces that happen to be fresh fruit.
  5. Change those neighboring fresh pieces into rotten pieces and remove them from the fresh count.
  6. Collect these newly rotten pieces into a next-up group so they can spread the rot in the following minute.
  7. Once you finish checking all neighbors for the current group, advance the timer by one minute and move on to the next group of newly rotten pieces.
  8. Repeat the process of spreading the rot outward minute by minute until no more fresh pieces can be reached.
  9. Check if there are any fresh pieces left over; if so, it is impossible to reach them, so return a failure signal.
  10. If no fresh pieces remain, return the final timer count representing the total minutes it took for the rot to spread everywhere.

Code Implementation

from collections import deque


def oranges_rotting(grid_matrix):
    row_count = len(grid_matrix)
    column_count = len(grid_matrix[0])
    queue_for_rotten = deque()
    fresh_orange_count = 0
    elapsed_minutes = 0

    for row_index in range(row_count):
        for col_index in range(column_count):
            if grid_matrix[row_index][col_index] == 2:
                queue_for_rotten.append((row_index, col_index))
            elif grid_matrix[row_index][col_index] == 1:
                fresh_orange_count += 1

    # Multi-source BFS requires starting simultaneously from all initially rotten oranges.
    while queue_for_rotten and fresh_orange_count > 0:
        for _ in range(len(queue_for_rotten)):
            current_row, current_col = queue_for_rotten.popleft()
            neighbor_directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]

            for row_offset, col_offset in neighbor_directions:
                neighbor_row = current_row + row_offset
                neighbor_col = current_col + col_offset

                if 0 <= neighbor_row < row_count and 0 <= neighbor_col < column_count:
                    if grid_matrix[neighbor_row][neighbor_col] == 1:
                        grid_matrix[neighbor_row][neighbor_col] = 2
                        queue_for_rotten.append((neighbor_row, neighbor_col))
                        fresh_orange_count -= 1

        elapsed_minutes += 1

    # If any fresh oranges remain unreachable, rotting the entire grid is impossible.
    if fresh_orange_count > 0:
        return -1

    # The accumulated timer represents the total minutes needed for all oranges to rot.
    return elapsed_minutes

Big(O) Analysis

Time Complexity
O(R * C) – The time complexity is driven by a multi-directional BFS traversal across a grid with R rows and C columns, where every cell is visited and pushed into the queue at most once. Initially, scanning the grid takes R * C operations to count fresh oranges and collect all rotten ones. During the BFS wave propagation, each rotten orange inspects its up to four immediate neighbors, resulting in constant time work per cell. Across the entire grid of size n where n = R * C, the total operations scale linearly with the number of cells, approximating n * 1 steps and simplifying to O(n).
Space Complexity
O(N) – Let N be the total number of cells in the grid, which accounts for both rotten and fresh oranges. The algorithm uses a queue data structure to gather the rotten pieces and newly rotten pieces for simultaneous wave processing. In the worst-case scenario where almost all oranges are rotten initially, this queue will store up to N elements. Therefore, the auxiliary space consumed by the queue scales linearly with the total grid size.

Edge Cases

Grid contains only fresh oranges and zero rotten oranges
How to Handle:
The queue starts empty with no rotten oranges, so the algorithm returns negative one if fresh oranges remain.
Grid contains only rotten oranges and zero fresh oranges
How to Handle:
The initial fresh count is zero, so the algorithm immediately returns zero minutes elapsed.
Grid contains isolated fresh oranges completely blocked by empty cells
How to Handle:
The multi-source breadth first search will exhaust without reaching them, leaving fresh oranges and returning negative one.
Minimum sized one by one grid with a single fresh orange
How to Handle:
The initial fresh count is one and rotten count is zero, returning negative one since it can never rot.
Minimum sized one by one grid with a single rotten orange
How to Handle:
The initial fresh count is zero, so the algorithm bypasses traversal and correctly returns zero minutes.
Grid with all empty cells and no oranges at all
How to Handle:
Both fresh and rotten counts start at zero, allowing the algorithm to return zero minutes instantly.
Maximum sized grid where all fresh oranges rot in a single connected component
How to Handle:
Breadth first search scales linearly with the number of cells visiting each grid coordinate at most once efficiently.
Multiple disjoint rotten oranges rotting separate clusters simultaneously
How to Handle:
Pushing all initial rotten oranges into the queue simultaneously ensures correct parallel level order traversal.
0/75 completed