Browse Curriculum
FAANGPrep Sprint
Medium

Rotting Oranges

Determine the minimum time required to rot all oranges.

Problem Understanding

You have a grid with:

  • 0: Empty cell
  • 1: Fresh orange
  • 2: Rotten orange

Every minute, a rotten orange infects its 4-directionally adjacent fresh neighbors. Return minimum minutes until no fresh orange remains. If impossible, return -1.

Algorithm Strategy

This simulates a process expanding over time, which is classic BFS.

  1. Multi-source: Start with ALL initially rotten oranges in the Queue.
  2. Count Fresh: Count total fresh oranges initially. If 0, return 0.
  3. Level-by-Level: Process the queue layer by layer (minutes). Each layer spreads rot to neighbors.
    • Decrement fresh_count whenever a fresh orange rots.
  4. Completion: If queue empty and fresh_count == 0, return time. Else return -1.

Interactive Visualization

Step 1 / 1

Initializing...

1x

Watch how the infection spreads from multiple sources simultaneously.

Stop Guessing, Start Mastering.

Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.