#1861
Medium Algorithms Rotating the box
Array Two Pointers Matrix
79.2% acceptance
Feb 25, 2026
1625
82
You are given an m x n matrix of characters boxGrid representing a side-view of a box. Each cell is '#' (stone), '*' (obstacle), or '.' (empty).
The box is rotated 90 degrees clockwise, causing stones to fall due to gravity. Return the n x m matrix representing the box after rotation.
Solution
Rust
Time O(n * m)
Space O(n * m)
impl Solution {
pub fn rotate_the_box(mut box_grid: Vec<Vec<char>>) -> Vec<Vec<char>> {
let m = box_grid.len();
let n = box_grid[0].len();
// Apply gravity: stones fall to the right in each row
for row in box_grid.iter_mut() {
let mut empty = n - 1; // rightmost available position
for col in (0..n).rev() {
match row[col] {
'#' => {
row[col] = '.';
row[empty] = '#';
if empty > 0 { empty -= 1; }
}
'*' => {
if col > 0 { empty = col - 1; }
}
_ => {}
}
}
}
// Rotate 90 degrees clockwise: result[j][m-1-i] = box[i][j]
// Result is n rows x m cols
let mut result = vec![vec!['.'; m]; n];
for i in 0..m {
for j in 0..n {
result[j][m - 1 - i] = box_grid[i][j];
}
}
result
}
}