← Meta (Facebook) bank

Meta (Facebook) · Question 63

Rotting Oranges

Pythoncode⏱ O(mn)💾 O(mn)
Product-based

Problem

You are given grid with fresh and rotten oranges. Find minimum time for all oranges to rot.

Approach

Multi-source BFS from all rotten oranges, tracking minutes per layer.

Time O(mn)Space O(mn)

How it works

  1. 1Seed the queue with every rotten orange.
  2. 2Each BFS layer rots neighbours: one minute.
  3. 3Leftover fresh means impossible: -1.

Sample input / output

Input:
3
2 1 1
1 1 0
0 1 1
Output:
4

Constraints

1 <= m, n <= 10; cells 0/1/2.

Solution — read it, then walk it

Time O(mn)Space O(mn)Loops 5Branches 5Returns 2source · Python
Scroll sideways for wide charts — the view follows the active step.
↻ repeatyesnoyes↻ repeat↻ repeatyesno↻ repeatyes↻ repeat↻ repeat↻ repeatyesnoSTARTfrom collections importdequeDEFINE orangesRotting(grid)m, n = len(grid),len(grid[0])q = deque()fresh = 0for i in range(m)for j in range(n)if grid[i][j] == 2q.append((i, j))if grid[i][j] == 1fresh += 1if fresh == 0RETURN 0minutes = 0dirs = [[-1, 0], [1, 0],[0, -1], [0, 1]]while qsize = len(q)for _ in range(size)x, y = q.popleft()for dx, dy in dirsnx, ny = x + dx, y + dyif 0 <= nx < m and 0<= ny < n andgrid[nx][ny] == 1grid[nx][ny] = 2fresh -= 1q.append((nx, ny))minutes += 1RETURN minutes - 1 if fresh== 0 else -1DEFINE main()import sysdata =sys.stdin.read().split()it = iter(data)m = int(next(it))grid = [[int(next(it)) for_ in range(m)] for _ inrange(m)]print(orangesRotting(grid))if __name__ =="__main__"main()END
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/37

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits