Rotating the Box

Medium Arrays & Hashing Two Pointer

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].length
  • 1 <= 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.

00:00
Testcase

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.

ApproachTimeSpace
Rotate, then simulate fallingO(m · n²)O(m · n)
Optimal (two pointers per row, then rotate)O(m · n)O(m · n)

1Rotate, then simulate falling

TimeO(m · n²)Each pass costs m · n and a stone may need up to n passes to reach the floor.
SpaceO(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.

  1. res[j][m - 1 - i] = box[i][j] for every cell.
  2. 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.
  3. 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;
    }
}

2Optimal (two pointers per row, then rotate)

TimeO(m · n)Each cell is visited once in the scan and once in the rotation.
SpaceO(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.

  1. For each row i: empty = n - 1.
  2. 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--.
  3. 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;
    }
}

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).