Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

Coding · Graphs

Minutes until every orange rots

Medium · Target 18 minutes · Graphs · Type asked atAmazonMicrosoftBloomberg

A grid is a list of equal-length strings of '0' (empty), '1' (fresh orange) and '2' (rotten orange). Every minute, each fresh orange that shares an edge with a rotten one becomes rotten. Return the number of minutes until no fresh orange remains, 0 if there is none to begin with, or -1 if some fresh orange can never rot.

Examples

InputOutputWhy
grid = ["211", "110", "011"]4The rot spreads from the top-left corner and reaches the bottom-right orange in the fourth minute.
grid = ["211", "011", "101"]-1The bottom-left orange has no neighbour that can ever rot.
grid = ["02"]0No fresh oranges: nothing to wait for.

Constraints

  • 1 ≤ rows, cols ≤ 300
  • Every row has the same length
  • Cells are '0', '1' or '2'

Hints

Hint 1

Each minute is one step of a breadth-first search. Where does the search start?

Hint 2

Put every rotten orange in the queue at the start, all at distance 0: a search from many sources at once.

Hint 3

Count the fresh oranges first. Each minute, the newly rotten ones are the next ring. Stop when the queue empties; if fresh ones remain, return −1.

Where people lose marks

  • Starting a separate search from each rotten orange: correct, and quadratic.
  • Counting the final ring, which rots nothing, as a minute: off by one.
  • Returning the minutes without checking that every fresh orange was reached.
  • Rotting oranges in place while still reading the same minute's grid, so the rot travels several cells in one minute.
Console⌘/Ctrl + Enter runs

Write a solution and run it against the real test table.


Keep going

Preparing for a real process? Quant interview preparation, or book a free 20-minute call.