Rotating the Box (LeetCode 1861): Solution and Explanation

Medium
Array
Two pointers
Matrix

A side view of a box holds stones '#', fixed obstacles '*' and empty cells '.'. Turn the box 90 degrees clockwise, let the stones fall until they hit an obstacle, a stone or the floor, and return the new n x m picture.

Intuition

You could rotate first and then simulate gravity column by column. That works, but there is a neater order.

Think about where the floor ends up. Rotating clockwise turns the right end of every row into the bottom of the matching column. So a stone that falls after the rotation is a stone that slides right inside its row before it.

Rows are independent, and inside a row stones can never pass an obstacle. Scan each row from right to left while remembering empty, the rightmost cell a stone could still reach. A stone moves straight to empty; an obstacle resets empty to the cell just left of it.

After every row has settled, copy the grid into its rotated position. Input cell (r, c) lands at output (c, m - 1 - r).

Approach: Slide right with an empty pointer, then rotate

  1. For each row, set empty = n - 1.
  2. Scan c from n - 1 down to 0.
  3. If the cell is an obstacle, set empty = c - 1.
  4. If the cell is a stone, clear it, place a stone at empty, then decrement empty.
  5. Build an n x m result with result[c][m - 1 - r] = boxGrid[r][c] and return it.

Step-by-step example

boxGrid = [["#",".","*","."],["#","#","*","."]]
  1. Row 0: empty = 3. Column 3 is empty. Column 2 is an obstacle, so empty = 1. Column 0 is a stone: it slides to column 1, empty = 0. Row 0 becomes [".","#","*","."].
  2. Row 1: empty = 3. Column 2 is an obstacle, so empty = 1. Column 1 is a stone already at empty, it stays, empty = 0. Column 0 is a stone at empty, it stays.
  3. The settled grid is [[".","#","*","."],["#","#","*","."]].
  4. Rotate: input column 0 read from the bottom row up is ["#","."], which is output row 0. Column 1 gives ["#","#"], column 2 gives ["*","*"], column 3 gives [".","."].
  5. The answer is [["#","."],["#","#"],["*","*"],[".","."]].

Code: Python, Java, C++

1class Solution:
2    def rotateTheBox(self, boxGrid: List[List[str]]) -> List[List[str]]:
3        m, n = len(boxGrid), len(boxGrid[0])
4        for row in boxGrid:
5            empty = n - 1
6            for c in range(n - 1, -1, -1):
7                if row[c] == '*':
8                    empty = c - 1
9                elif row[c] == '#':
10                    row[c], row[empty] = '.', '#'
11                    empty -= 1
12        result = [[boxGrid[m - 1 - r][c] for r in range(m)] for c in range(n)]
13        return result
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(m x n)

Each row is scanned once and each cell is copied once during the rotation.

Space

O(m x n)

The rotated output has m x n cells. Apart from it, only the empty pointer is used.

Other approaches

Rotate first, then drop stones per column (time O(m x n), space O(m x n))

Build the rotated grid, then for every column scan from the bottom up with the same empty pointer idea. Identical complexity; the only difference is the order of the two steps.

Repeated one-step falls (time O(m x n x max(m, n)), space O(m x n))

Keep moving any stone with an empty cell below it down by one until nothing changes. Easy to reason about, but a long column can need many sweeps, up to O(m x n x max(m, n)).

Common mistakes

  • Sliding stones left. With a clockwise turn the right end of each row becomes the floor.
  • Rotating counterclockwise by mistake. Clockwise maps (r, c) to (c, m - 1 - r); counterclockwise would map it to (n - 1 - c, r).
  • Writing the stone to empty before clearing its old cell. When empty == c the stone does not move, and clearing afterwards would erase it.
  • Forgetting to reset empty at an obstacle, which lets stones jump over it.

Frequently asked questions

Why can I apply gravity before rotating?

The rotation only relabels cells. Falling down in the rotated box is the same movement as sliding right in the original rows, so doing it first gives the same final picture.

Why scan each row from right to left?

The right end is the floor. Scanning from it means every stone you meet can be placed at the lowest free cell immediately, because everything to its right has already settled.

Does the guarantee about stones resting on something matter for the algorithm?

No. It only describes a valid starting picture. The slide-then-rotate method works for any arrangement.

What is the complexity?

O(m x n) time, and O(m x n) space for the returned matrix.