← Lyft Interview InsightsSoftware Engineer
Use a multi-source BFS starting simultaneously from all initially rotten oranges, treating them as the first layer of the queue. Track elapsed minutes as BFS levels and count remaining fresh oranges to determine if the result is -1. This approach naturally models the simultaneous spread of rot each minute.
Pro tip: Mention that multi-source BFS is the key insight here — initializing the queue with ALL rotten oranges at once (not one at a time) is what correctly simulates parallel spreading, and distinguishing this from single-source BFS shows algorithmic maturity.
Scan the grid to enqueue all initially rotten oranges (value 2) into the BFS queue and count all fresh oranges (value 1). This sets up the multi-source starting state.
Process the queue level by level, where each level represents one minute. For each rotten orange, spread rot to its 4 adjacent fresh neighbors, decrement the fresh count, and enqueue the newly rotten cells.
Increment a minutes counter after processing each complete BFS level (not after each individual cell). Only increment time if the current level actually produced newly rotten oranges.
After BFS completes, check if the fresh orange count is zero. If fresh count > 0, return -1 (isolated fresh oranges exist); otherwise return the elapsed minutes.
State that time and space complexity are both O(M×N) where M and N are grid dimensions, since every cell is visited at most once and the queue can hold at most all cells.
AI-generated suggestions, not part of the candidate's original notes. May be inaccurate — verify before relying on them.