Description
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.
Example 1:

Input: boxGrid = [["#",".","#"]] Output: [["."], ["#"], ["#"]]
Example 2:

Input: boxGrid = [["#",".","*","."], ["#","#","*","."]] Output: [["#","."], ["#","#"], ["*","*"], [".","."]]
Example 3:

Input: boxGrid = [["#","#","*",".","*","."], ["#","#","#","*",".","."], ["#","#","#",".","#","."]] Output: [[".","#","#"], [".","#","#"], ["#","#","*"], ["#","*","."], ["#",".","*"], ["#",".","."]]
Constraints:
m == boxGrid.lengthn == boxGrid[i].length1 <= m, n <= 500boxGrid[i][j]is either'#','*', or'.'.
Solutions
This is the most optimized solution, using a clever in-place technique that processes each row from right to left while building the rotated result: for each stone (#), it bubbles it to the rightmost available position (max), then places it in the result grid at the rotated coordinate; when an obstacle (*) is encountered, it resets the rightmost boundary (max = col - 1) since stones cannot pass through obstacles—this single-pass algorithm efficiently handles both rotation and gravity simultaneously with minimal operations.
/**
* @param {character[][]} box
* @return {character[][]}
*/
var rotateTheBox = function(box) {
const m = box.length;
const n = box[0].length;
const res = Array.from({ length: n }, () => Array(m).fill('.'));
for (let row = 0; row < m; row++) {
const irow = m - 1 - row;
let max = n - 1;
for (let col = max; col >= 0; col--) {
if (box[row][col] === '#') {
box[row][col] = res[col][irow] = box[row][max];
box[row][max] = res[max][irow] = '#';
max--;
} else if (box[row][col] === '*') {
res[col][irow] = box[row][col];
max = col - 1;
}
}
}
return res;
};