LeetCode 1861: Rotating the Box Solution
Master LeetCode problem 1861 (Rotating the Box), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1861. Rotating the Box
Problem Explanation
Explanation
To solve this problem, we can iterate over each column from right to left. For each column, we can simulate the falling of stones due to gravity. Starting from the bottom row, if we encounter a stone ('#'), we try to move it downwards until it lands on an obstacle ('*') or another stone.
We can achieve this by maintaining a pointer to track the current position of the stone. If the position below the current position is empty ('.'), we keep moving the stone downwards. If the position below is an obstacle or another stone, we stop moving the stone and update the grid accordingly.
After processing all columns, we will obtain the final state of the box after rotation.
- Time Complexity: O(m*n) where m is the number of rows and n is the number of columns in the grid.
- Space Complexity: O(1) as we are modifying the input grid in place.
Solution Code
class Solution {
public char[][] rotateTheBox(char[][] boxGrid) {
int m = boxGrid.length;
int n = boxGrid[0].length;
for (int col = n - 1; col >= 0; col--) {
int currRow = m - 1;
int stonePos = m - 1;
while (currRow >= 0) {
if (boxGrid[currRow][col] == '#') {
boxGrid[currRow][col] = '.';
boxGrid[stonePos][col] = '#';
stonePos--;
} else if (boxGrid[currRow][col] == '*') {
stonePos = currRow - 1;
}
currRow--;
}
}
return boxGrid;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1861 (Rotating the Box)?
This page provides optimized solutions for LeetCode problem 1861 (Rotating the Box) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1861 (Rotating the Box)?
The time complexity for LeetCode 1861 (Rotating the Box) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1861 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1861 in Java, C++, or Python.