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 - Optimal Solution INPUT Original Box (3x3 matrix) . # # . # * . # . Legend: # Stone * Obstacle . Empty 90° clockwise ALGORITHM STEPS 1 Process each row Move stones right to nearest obstacle/edge 2 Apply gravity in row Two-pointer: track empty slot and scan stones 3 Rotate 90° clockwise result[j][m-1-i] = box[i][j] 4 Return new matrix n x m dimensions Row Processing Example: [. # #] --> [. # #] [. # *] --> [. # *] [. # .] --> [. . #] Stones fall right first then rotate the box FINAL RESULT Rotated Box (3x3 matrix) # . . # # * # # . Output Array: [["#",".","."], ["#","#","*"], ["#","#","."]] OK - Complete Gravity Key Insight: Process stones BEFORE rotation: In original rows, gravity acts horizontally (rightward). Use two-pointer technique: scan right-to-left, track rightmost empty position before each obstacle. Time: O(m*n) | Space: O(n*m) for result. Obstacles reset the empty position tracker. TutorialsPoint - Rotating the Box | Optimal Solution
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