1861. Rotating the Box
Approach
Simulate gravity rightward per row; then rotate the matrix 90° clockwise.
Key Techniques
Array problems involve manipulating elements stored in a contiguous block of memory. Key techniques include two-pointer traversal, prefix sums, sliding windows, and in-place partitioning. In C#, arrays are zero-indexed and fixed in size — use List<T> when you need dynamic resizing.
The two-pointer technique places pointers at different positions (often the two ends) and moves them toward each other. It turns O(n²) nested loops into O(n) sweeps for problems like pair sums, removing duplicates, and container capacity. Works best on sorted or partitioned arrays.
Matrix problems often involve BFS/DFS flood fill, dynamic programming on 2D grids, or spiral/diagonal traversal. For row × column DP, break it into 1D sub-problems column by column. Common pitfalls: boundary checks and modifying the input matrix in-place.
// Approach: Simulate gravity rightward per row; then rotate the matrix 90° clockwise.
// Time: O(mn) Space: O(mn)
public class Solution
{
public char[][] RotateTheBox(char[][] box)
{
int m = box.Length;
int n = box[0].Length;
char[][] ans = new char[n][];
for (int i = 0; i < n; i++)
{
ans[i] = new char[m];
Array.Fill(ans[i], '.');
}
for (int i = 0; i < m; ++i)
{
for (int j = n - 1, k = n - 1; j >= 0; --j)
{
if (box[i][j] != '.')
{
if (box[i][j] == '*')
k = j;
ans[k--][m - i - 1] = box[i][j];
}
}
}
return ans;
}
}