In a grid, 0 is empty, 1 is a fresh orange and 2 a rotten one. Every minute, fresh oranges next to rotten ones rot. Return the minutes until no fresh orange remains, or -1 if that never happens.
Before you code
The rot spreads from all rotten oranges at once. Starting all of them in the queue together gives every fresh orange its distance to the nearest rotten one.
Hints
- Enqueue every rotten orange with time 0 and count the fresh ones.
- BFS level by level; each level is one minute. Rot fresh neighbors as you enqueue them, decrementing the fresh count.
- If the fresh count is not 0 at the end, return -1.
Production & complexity notes
When solving Rotting oranges on LeetCode (medium), always state your loop or recursion invariant before writing code. Verify how your chosen data structure behaves on degenerate inputs (single-element inputs, all-duplicate keys, strictly monotonic sequences, or maximum constraint sizes up to $10^5$ elements). In production interviews, pair your implementation with an explicit time and auxiliary space complexity proof, explain why alternative brute-force approaches violate the latency budget, and trace how cache locality and memory allocation overhead affect wall-clock throughput on real hardware. Review the step-by-step memory trace in Breadth-first search to reinforce the underlying pattern.
What it practices
BFS from several sources at once, from Breadth-first search.