Skip to the solution
MediumDSA13 min read

How do you solve the Rotting Oranges problem with multi-source BFS?

292 views

The problem

Question presented to candidate: "You have a grid where 0 is an empty cell, 1 is a fresh orange and 2 is a rotten orange. Every minute, each rotten orange rots the fresh oranges directly up, down, left and right of it. Return the minimum number of minutes until no fresh orange is left, or -1 if that is impossible. Please solve it in Python."

What a strong answer should cover:

  • Seeing the grid as a graph and the spread as BFS levels: level k = the oranges that rot at minute k.
  • Multi-source BFS: put every rotten orange in the queue at time 0 before the loop โ€” not one BFS per rotten orange.
  • Counting fresh oranges up front to detect the -1 case, and the 0 case when nothing is fresh.
  • O(rows ร— cols) time and space, versus O(minutes ร— rows ร— cols) for a minute-by-minute simulation.
  • Python specifics: collections.deque with popleft(), for _ in range(len(queue)) to process exactly one level, building a 2D grid with a comprehension (never [[-1] * cols] * rows), and saying whether you mutate the caller's grid.

Clarifying questions expected:

  • Four directions or eight? What if there are no fresh oranges?
  • May I modify the input grid?

Code / implementation expected: Yes โ€” an oranges_rotting(grid) function in Python using multi-source BFS, tested on the impossible case and the no-fresh case.

  • dsa
  • graph
  • bfs
  • grid

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

13 min read ยท 10 sections

Python code

Edit the code and run it here. Each printed line with an expected value becomes a test.

PythonMulti-source BFS on six grids, plus the minute each orange rotted
PythonSimulation vs one BFS per rotten orange vs multi-source BFS: counting the work

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 103 of 154 in DSA

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All DSA questions
Up nextMedium

How do you design a min stack with O(1) getMin?

Continue