Python | Two Pointers (Sliding Window)
see the Successfully Accepted Submission\n\n# Code\npython3 []\nclass Solution:\n    def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]:\n        m
[see the Successfully Accepted Submission](https://leetcode.com/problems/rotating-the-box/submissions/1460386611/?envType=daily-question&envId=2024-11-23)\n\n# Code\n```python3 []\nclass Solution:\n    def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]:\n        m, n = len(box), len(box[0])\n        \n        # Process each row to simulate gravity\n        for row in box:\n            empty_slot = n - 1  # Start from the rightmost column\n            \n            for col in range(n - 1, -1, -1):  # Traverse the row from right to left\n                if row[col] == \'#\':  # Stone\n                    row[col], row[empty_slot] = row[empty_slot], row[col]\n                    empty_slot -= 1\n                elif row[col] == \'*\':  # Obstacle\n                    empty_slot = col - 1\n        \n        # Rotate the box clockwise\n        rotated_box = [[None] * m for _ in range(n)]  # Create a rotated matrix\n        for i in range(m):\n            for j in range(n):\n                rotated_box[j][m - 1 - i] = box[i][j]\n        \n        return rotated_box\n\n```\n\n\n# Solution Explanation\n\n## Simulating Gravity:\n\n1. For each row, traverse from right to left.\n2. Maintain an `empty_slot` pointer to indicate where the next stone should "fall."\n3. When encountering a stone (`#`), swap it with the element at the `empty_slot`.\n4. When encountering an obstacle (`*`), reset the `empty_slot` pointer to one column before the obstacle.\n\n---\n\n## Rotating the Matrix:\n\n1. Create a new matrix of size `n x m` to hold the rotated box.\n2. For each element in the original box, map it to its new position in the rotated matrix:\n   - The element at `box[i][j]` is placed at `rotated_box[j][m - 1 - i]`.\n\n---\n\n## Time Complexity:\n\n1. Processing gravity for all rows: \\( O(m \\times n) \\).\n2. Rotating the matrix: \\( O(m \\times n) \\).\n3. Overall complexity: \\( O(m \\times n) \\).\n\n---\n\n## Space Complexity:\n\n1. Output matrix for rotation: \\( O(m \\times n) \\).\n2. Additional space is constant apart from the result.\n\n\n\n\n![image](https://assets.leetcode.com/users/images/b1e4af48-4da1-486c-bc97-b11ae02febd0_1696186577.992237.jpeg)
['Python3']