Topics/Matrices & Grids/Rotting oranges

Pattern

Rotting oranges

Rotting oranges is a reusable approach under Matrices & Grids. Once you recognize the shape of the input and the ask, this pattern gives you a standard plan instead of inventing a new algorithm from scratch.

Matrices & GridsPatternsPattern

When to use it

Reach for Rotting oranges when a matrices & grids problem matches the cues in this lesson — especially after you’ve ruled out a brute-force nested scan.

How it works

  1. Restate the Matrices & Grids problem in one sentence and name the constraint that Rotting oranges exploits.
  2. Sketch the invariant Rotting oranges maintains (what stays true after each step).
  3. Walk a tiny example by hand, writing the state after every update.
  4. Translate that walk into code in your interview language, then list edge cases.

Solution

Reference implementation in C#, Python, Java, JavaScript, and C++.

Exact solutionRotting oranges

Why interviewers care

Interviewers grade pattern recognition. Naming Rotting oranges early shows you can classify the problem inside Patterns.

Drill Rotting oranges with Matrices & Grids problems — filter the bank and solve 2–3 Easy/Medium items while saying the invariant out loud.

Watch-outs

  • !Row/col swap bugs
  • !Mutating input unexpectedly
  • !Boundary checks

Practice this

Related Matrices & Grids problems — open any one and apply Rotting oranges.

Search bank →

More under Matrices & Grids

← Back to Matrices & Grids lesson