Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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:
'#''*''.'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 '.'.Problem summary: 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.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Two Pointers
[["#",".","#"]]
[["#",".","*","."],["#","#","*","."]]
[["#","#","*",".","*","."],["#","#","#","*",".","."],["#","#","#",".","#","."]]
Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #1861: Rotating the Box
class Solution {
public char[][] rotateTheBox(char[][] box) {
int m = box.length, n = box[0].length;
char[][] ans = new char[n][m];
for (int i = 0; i < m; ++i) {
for (int j = 0; j < n; ++j) {
ans[j][m - i - 1] = box[i][j];
}
}
for (int j = 0; j < m; ++j) {
Deque<Integer> q = new ArrayDeque<>();
for (int i = n - 1; i >= 0; --i) {
if (ans[i][j] == '*') {
q.clear();
} else if (ans[i][j] == '.') {
q.offer(i);
} else if (!q.isEmpty()) {
ans[q.pollFirst()][j] = '#';
ans[i][j] = '.';
q.offer(i);
}
}
}
return ans;
}
}
// Accepted solution for LeetCode #1861: Rotating the Box
func rotateTheBox(box [][]byte) [][]byte {
m, n := len(box), len(box[0])
ans := make([][]byte, n)
for i := range ans {
ans[i] = make([]byte, m)
}
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
ans[j][m-i-1] = box[i][j]
}
}
for j := 0; j < m; j++ {
q := []int{}
for i := n - 1; i >= 0; i-- {
if ans[i][j] == '*' {
q = []int{}
} else if ans[i][j] == '.' {
q = append(q, i)
} else if len(q) > 0 {
ans[q[0]][j] = '#'
q = q[1:]
ans[i][j] = '.'
q = append(q, i)
}
}
}
return ans
}
# Accepted solution for LeetCode #1861: Rotating the Box
class Solution:
def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]:
m, n = len(box), len(box[0])
ans = [[None] * m for _ in range(n)]
for i in range(m):
for j in range(n):
ans[j][m - i - 1] = box[i][j]
for j in range(m):
q = deque()
for i in range(n - 1, -1, -1):
if ans[i][j] == '*':
q.clear()
elif ans[i][j] == '.':
q.append(i)
elif q:
ans[q.popleft()][j] = '#'
ans[i][j] = '.'
q.append(i)
return ans
// Accepted solution for LeetCode #1861: Rotating the Box
struct Solution;
impl Solution {
pub fn rotate_the_box(b: Vec<Vec<char>>) -> Vec<Vec<char>> {
let n = b.len();
let m = b[0].len();
let mut a = vec![];
for _ in 0..m {
a.push(vec!['.'; n]);
}
for i in 0..n {
let mut x = m;
let mut y = m;
for _j in 0..m {
match b[i][x - 1] {
'.' => {}
'*' => {
a[x - 1][n - 1 - i] = '*';
y = x - 1;
}
'#' => {
a[y - 1][n - 1 - i] = '#';
y -= 1;
}
_ => {}
}
x -= 1;
}
}
a
}
}
#[test]
fn test() {
let b: Vec<Vec<char>> = vec_vec_char![['#', '.', '#']];
let a: Vec<Vec<char>> = vec_vec_char![['.'], ['#'], ['#']];
assert_eq!(Solution::rotate_the_box(b), a);
let b: Vec<Vec<char>> = vec_vec_char![['#', '.', '*', '.'], ['#', '#', '*', '.']];
let a: Vec<Vec<char>> = vec_vec_char![['#', '.'], ['#', '#'], ['*', '*'], ['.', '.']];
assert_eq!(Solution::rotate_the_box(b), a)
}
// Accepted solution for LeetCode #1861: Rotating the Box
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #1861: Rotating the Box
// class Solution {
// public char[][] rotateTheBox(char[][] box) {
// int m = box.length, n = box[0].length;
// char[][] ans = new char[n][m];
// for (int i = 0; i < m; ++i) {
// for (int j = 0; j < n; ++j) {
// ans[j][m - i - 1] = box[i][j];
// }
// }
// for (int j = 0; j < m; ++j) {
// Deque<Integer> q = new ArrayDeque<>();
// for (int i = n - 1; i >= 0; --i) {
// if (ans[i][j] == '*') {
// q.clear();
// } else if (ans[i][j] == '.') {
// q.offer(i);
// } else if (!q.isEmpty()) {
// ans[q.pollFirst()][j] = '#';
// ans[i][j] = '.';
// q.offer(i);
// }
// }
// }
// return ans;
// }
// }
Use this to step through a reusable interview workflow for this problem.
Two nested loops check every pair of elements. The outer loop picks one element, the inner loop scans the rest. For n elements that is n × (n−1)/2 comparisons = O(n²). No extra memory — just two loop variables.
Each pointer traverses the array at most once. With two pointers moving inward (or both moving right), the total number of steps is bounded by n. Each comparison is O(1), giving O(n) overall. No auxiliary data structures are needed — just two index variables.
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Advancing both pointers shrinks the search space too aggressively and skips candidates.
Usually fails on: A valid pair can be skipped when only one side should move.
Fix: Move exactly one pointer per decision branch based on invariant.