PPractick

DSA interview question

Rotting Oranges

Medium · Data structures · Topics: graph, bfs, matrix

The problem

A crate of oranges is a grid: 0 is empty, 1 is a fresh orange, 2 is a rotten orange. Every minute, each rotten orange rots its 4-directionally adjacent fresh neighbours. How many minutes until no fresh orange remains? Return −1 if some can never rot. All rotten oranges spread at the same time, so this is a multi-source BFS: put every initially rotten orange in the queue at minute 0 and process the queue level by level, with each level being one minute.

Example: [[2,1,1], [1,1,0], [0,1,1]] → 4.

Function signature

int orangesRotting(vector<vector<int>> grid);

Test cases

InputOutputExplanation
[[2,1,1],[1,1,0],[0,1,1]]4The bottom-right orange rots last
[[2,1,1],[0,1,1],[1,0,1]]-1The bottom-left orange is cut off
[[2,2],[1,1],[0,0],[2,0]]1Several starting points at once
[[0,2]]0No fresh oranges to begin with
[[1]]-1No rotten orange to start the spread

(Confirm: spreading is 4-directional and simultaneous; 0 if there are no fresh oranges; grid up to 10 × 10.)

How interviewers phrase it

Clarifying questions to ask

  1. 4-directional? (Yes.)
  2. What if there are no fresh oranges at all? (0.)
  3. Do all rotten oranges spread simultaneously? (Yes, which is why it's multi-source BFS.)

Follow-ups to expect

  1. "Why multi-source BFS?"
  2. "How do you count minutes?"
  3. "How do you detect −1?"
  4. "Why not BFS from each rotten orange separately?"
  5. "Complexity?"

Practise questions like this with a real engineer

On Practick another engineer interviews you live for 60 minutes on a question from this bank. They have the full interviewer guide beside the call: the expected answer to every follow-up, hints to give if you stall, and a scoring rubric. You get the model solution once the session settles. It is free: interview someone for an hour and you have earned your own.

Book a free mock interview

Related questions

All 474 dsa interview questions

DSA mock interviews · System design interview questions · Free mock interview practice · Browse interviewers · Sign in