Magicsheet logo

Rotating the Box

Medium
100%
Updated 6/1/2025

Rotating the Box

What is this problem about?

The Rotating the Box interview question gives you a 2D grid representing a box filled with stones (#), empty spaces (.), and obstacles (*). Stones fall to the right due to gravity (before rotating). After applying gravity, rotate the box 90 degrees clockwise. Return the resulting grid. This combines physics simulation with matrix rotation.

Why is this asked in interviews?

This problem is asked at Uber, Microsoft, Meta, Roblox, Amazon, Google, and Capital One because it chains two operations: a physics simulation (gravity) and a matrix transformation (rotation). Both individually are standard interview problems — "settle stones" and "rotate matrix." Combining them tests composability of algorithms and attention to sequential transformations. It has applications in game physics, cellular automata, and material simulation.

Algorithmic pattern used

The pattern is two-phase processing. Phase 1 — Apply gravity (rightward): for each row, use a two-pointer approach. Place a settle pointer at the rightmost column. Scan left to right (actually right to left): when a stone is found, place it at the settle position and clear its original position, then decrement settle. Reset settle when an obstacle is encountered (stones can't pass through obstacles). Phase 2 — Rotate 90° clockwise: apply the standard transpose-then-reverse-each-row technique.

Example explanation

Grid:

['#', '.', '.', '*']
['#', '#', '.', '.']

Phase 1 — Gravity (stones fall right within each row, blocked by *):

  • Row 0: * at col 3 is obstacle. Stone at col 0 → settles at col 2. Result: ['.', '.', '#', '*'].
  • Row 1: No obstacles. Stones at 0,1 → settle at 3,2. Result: ['.', '.', '#', '#'].

Grid after gravity:

['.', '.', '#', '*']
['.', '.', '#', '#']

Phase 2 — Rotate 90° CW (transpose + reverse rows): Result:

['.', '.']
['.', '.']
['#', '#']
['*', '#']

Common mistakes candidates make

  • Applying gravity left-to-right instead of right-to-left (stones fall to the right in this problem).
  • Not resetting the settle pointer when an obstacle is encountered.
  • Applying rotation before gravity instead of after.
  • Mixing up the rotation direction — 90° clockwise uses transpose + reverse rows.

Interview preparation tip

For the Rotating the Box coding problem, the array, matrix, and two-pointer interview pattern applies in two phases. Code each phase as a separate function for clarity. Interviewers at Meta and Google appreciate modular code: a apply_gravity(box) function and a rotate_90_cw(box) function, then compose them. Practice the gravity simulation on a row with an obstacle in the middle — it's the trickiest edge case.

Similar Questions