Rotating the Box - Problem

You are given an m x n matrix of characters boxGrid representing a side-view of a box. Each cell of the box is one of the following:

  • A stone '#'
  • A stationary obstacle '*'
  • Empty '.'

The box is rotated 90 degrees clockwise, causing some of the stones to fall due to gravity. Each stone falls down until it lands on an obstacle, another stone, or the bottom of the box. Gravity does not affect the obstacles' positions, and the inertia from the box's rotation does not affect the stones' horizontal positions.

It is guaranteed that each stone in boxGrid rests on an obstacle, another stone, or the bottom of the box.

Return an n x m matrix representing the box after the rotation described above.

Input & Output

Example 1 — Basic 3x3 Box
$ Input: boxGrid = [[".""#","#"],[".","#","#"],[".","#","."]]
Output: [["#",".","."],["#","#","*"],["#","#","."]]
💡 Note: After rotation, stones in columns 1&2 fall down. Column 0 has obstacle '*' blocking some stones.
Example 2 — Single Row
$ Input: boxGrid = [["#",".","*",".","#"]]
Output: [["#"],["#"],["*"],["."],["."]]
💡 Note: Single row becomes a column. Stones fall to bottom, obstacle stays in place.
Example 3 — All Obstacles
$ Input: boxGrid = [["*","*"],["*","*"]]
Output: [["*","*"],["*","*"]]
💡 Note: Obstacles don't move during rotation, so result is just rotated positions.

Constraints

  • m == boxGrid.length
  • n == boxGrid[i].length
  • 1 ≤ m, n ≤ 500
  • boxGrid[i][j] is either '.', '#', or '*'

Visualization

Tap to expand
Rotating the Box: Complete TransformationInput: 3×3 Box.##.##.*.Transformation ProcessROTATE90°CLOCKWISE+ Apply GravityOutput: 3×3 Result#..##*##.PROCESSRESULTm=3, n=3n=3, m=3Legend# = Stone* = Obstacle. = EmptyMatrix rotates 90° clockwise: (i,j) → (j, m-1-i)Stones fall down due to gravity until blocked by obstacle or edge
Understanding the Visualization
1
Input Box
3×3 matrix with stones (#), obstacles (*), and empty spaces (.)
2
Apply Gravity & Rotate
Stones fall due to gravity, then entire box rotates 90° clockwise
3
Final Result
3×3 result matrix showing new positions after transformation
Key Takeaway
🎯 Key Insight: Handle gravity first within rows using two pointers, then rotate - much simpler than rotating first then simulating falling stones individually
Asked in
Amazon 45 Microsoft 32 Google 28 Meta 22
35.4K Views
Medium Frequency
~25 min Avg. Time
987 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen