Rotating the Box
Rotating the Box is a medium arrays & hashing problem solved with the two pointer pattern.
The best approach, optimal (two pointers per row, then rotate), runs in O(m · n) time and O(m · n) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from rotate, then simulate falling up.
Problem
You get an m x n grid describing a box seen from the side. Each cell holds a stone '#', a fixed obstacle '*', or is empty '.'. The box is turned 90 degrees clockwise, and then gravity pulls every stone straight down until it lands on an obstacle, another stone, or the floor. Obstacles never move. Return the resulting n x m grid.
Examples
Example 1
- Input
box = [["#",".","*",".","#","."]]- Output
[["."],["#"],["*"],["."],["."],["#"]]- Why
- The first stone slides one cell until it rests on the obstacle; the second stone falls to the bottom.
Example 2
- Input
box = [["#","#","*"],[".","#","."]]- Output
[[".","#"],[".","#"],["#","*"]]- Why
- In the top row both stones are already blocked by the obstacle. In the second row the stone falls to the last cell. After rotating, the second row becomes the left column.
Constraints
m == box.length,n == box[i].length1 <= m, n <= 500- Each cell is '#' (stone), '*' (obstacle) or '.' (empty).
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (2 examples, or your own). Submit also runs 51 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Rotate, then simulate falling | O(m · n²) | O(m · n) |
| Optimal (two pointers per row, then rotate) | O(m · n) | O(m · n) |
1Rotate, then simulate falling
O(m · n²)Each pass costs m · n and a stone may need up to n passes to reach the floor.O(m · n)The rotated output grid.Build the rotated grid first, then repeatedly let any stone that has an empty cell directly below it drop one step, until a full pass moves nothing.
- res[j][m - 1 - i] = box[i][j] for every cell.
- Repeat: for each cell from bottom to top, if it is a stone and the cell below is empty, swap them and mark a change.
- Stop when a pass makes no change; return res.
class Solution {
public char[][] rotateTheBox(char[][] box) {
int m = box.length, n = box[0].length;
char[][] res = new char[n][m];
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++) res[j][m - 1 - i] = box[i][j];
boolean moved = true;
while (moved) {
moved = false;
for (int r = n - 2; r >= 0; r--)
for (int c = 0; c < m; c++)
if (res[r][c] == '#' && res[r + 1][c] == '.') {
res[r + 1][c] = '#';
res[r][c] = '.';
moved = true;
}
}
return res;
}
}class Solution:
def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]:
m, n = len(box), len(box[0])
res = [['.'] * m for _ in range(n)]
for i in range(m):
for j in range(n):
res[j][m - 1 - i] = box[i][j]
moved = True
while moved:
moved = False
for r in range(n - 2, -1, -1):
for c in range(m):
if res[r][c] == '#' and res[r + 1][c] == '.':
res[r + 1][c] = '#'
res[r][c] = '.'
moved = True
return resclass Solution {
public:
vector<vector<char>> rotateTheBox(vector<vector<char>>& box) {
int m = box.size(), n = box[0].size();
vector<vector<char>> res(n, vector<char>(m));
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++) res[j][m - 1 - i] = box[i][j];
bool moved = true;
while (moved) {
moved = false;
for (int r = n - 2; r >= 0; r--)
for (int c = 0; c < m; c++)
if (res[r][c] == '#' && res[r + 1][c] == '.') {
res[r + 1][c] = '#';
res[r][c] = '.';
moved = true;
}
}
return res;
}
};function rotateTheBox(box) {
const m = box.length, n = box[0].length;
const res = Array.from({ length: n }, () => new Array(m).fill('.'));
for (let i = 0; i < m; i++)
for (let j = 0; j < n; j++) res[j][m - 1 - i] = box[i][j];
let moved = true;
while (moved) {
moved = false;
for (let r = n - 2; r >= 0; r--)
for (let c = 0; c < m; c++)
if (res[r][c] === '#' && res[r + 1][c] === '.') {
res[r + 1][c] = '#';
res[r][c] = '.';
moved = true;
}
}
return res;
}2Optimal (two pointers per row, then rotate)
O(m · n)Each cell is visited once in the scan and once in the rotation.O(m · n)Only the output grid; the scan uses one pointer.Gravity after the rotation pushes stones to the right end of each original row. Scan each row from right to left keeping empty, the rightmost cell a stone can land in. An obstacle resets empty to just left of it; a stone moves to empty and empty steps left. Then write the rotated grid.
- For each row i: empty = n - 1.
- For j = n - 1 down to 0: if box[i][j] == '*', empty = j - 1; if it is '#', set box[i][j] = '.', box[i][empty] = '#', empty--.
- res[j][m - 1 - i] = box[i][j] for every cell; return res.
class Solution {
public char[][] rotateTheBox(char[][] box) {
int m = box.length, n = box[0].length;
for (int i = 0; i < m; i++) {
int empty = n - 1;
for (int j = n - 1; j >= 0; j--) {
if (box[i][j] == '*') empty = j - 1;
else if (box[i][j] == '#') {
box[i][j] = '.';
box[i][empty] = '#';
empty--;
}
}
}
char[][] res = new char[n][m];
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++) res[j][m - 1 - i] = box[i][j];
return res;
}
}class Solution:
def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]:
m, n = len(box), len(box[0])
for i in range(m):
empty = n - 1
for j in range(n - 1, -1, -1):
if box[i][j] == '*':
empty = j - 1
elif box[i][j] == '#':
box[i][j] = '.'
box[i][empty] = '#'
empty -= 1
res = [['.'] * m for _ in range(n)]
for i in range(m):
for j in range(n):
res[j][m - 1 - i] = box[i][j]
return resclass Solution {
public:
vector<vector<char>> rotateTheBox(vector<vector<char>>& box) {
int m = box.size(), n = box[0].size();
for (int i = 0; i < m; i++) {
int empty = n - 1;
for (int j = n - 1; j >= 0; j--) {
if (box[i][j] == '*') empty = j - 1;
else if (box[i][j] == '#') {
box[i][j] = '.';
box[i][empty] = '#';
empty--;
}
}
}
vector<vector<char>> res(n, vector<char>(m));
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++) res[j][m - 1 - i] = box[i][j];
return res;
}
};function rotateTheBox(box) {
const m = box.length, n = box[0].length;
for (let i = 0; i < m; i++) {
let empty = n - 1;
for (let j = n - 1; j >= 0; j--) {
if (box[i][j] === '*') empty = j - 1;
else if (box[i][j] === '#') {
box[i][j] = '.';
box[i][empty] = '#';
empty--;
}
}
}
const res = Array.from({ length: n }, () => new Array(m).fill('.'));
for (let i = 0; i < m; i++)
for (let j = 0; j < n; j++) res[j][m - 1 - i] = box[i][j];
return res;
}Edge cases to test
- A single cell
- No stones, or no obstacles at all
- Stones stacked against an obstacle that already cannot move
- Obstacles at the very end of a row (the floor after rotation)
Hints
Hint 1
After a clockwise rotation, 'down' in the new grid is 'right' in the original row. Let the stones slide right in every row first, then rotate.
Hint 2
Rows are independent and obstacles split a row into segments. Scan each row from right to left, remembering the lowest empty cell a stone can drop into.
FAQ
What is the best time complexity for Rotating the Box?
Optimal (two pointers per row, then rotate) runs in O(m · n) time and O(m · n) extra space. Each cell is visited once in the scan and once in the rotation.
Which pattern does Rotating the Box use?
It is a arrays & hashing problem that uses the two pointer pattern. Other problems with the same pattern: Two Sum II - Input Array Is Sorted, Valid Triangle Number, Container With Most Water.
Is there a brute force solution for Rotating the Box?
Yes. Rotate, then simulate falling takes O(m · n²) time and O(m · n) space. Build the rotated grid first, then repeatedly let any stone that has an empty cell directly below it drop one step, until a full pass moves nothing.
Which edge cases should I test for Rotating the Box?
A single cell; No stones, or no obstacles at all; Stones stacked against an obstacle that already cannot move; Obstacles at the very end of a row (the floor after rotation).