Rotating the Box — LeetCode 1861 Python Solution
- Problem
- #1861
- Pattern
- Two Pointers
- Reading time
- 3 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- boxGrid = [["#",".","#"]]
- Output
- [["."],
Python solution
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(m \times n) |
| Space | O(m \times n) auxiliary |
Pattern: Two Pointers
Use the order already in the input to discard half the search space at every step. LeetCode 1861. Rotating the Box is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Two Pointers.
The two pointers guide has the Python template for the pattern and the 201 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1861. Rotating the Box?
- LeetCode 1861. Rotating the Box is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1861. Rotating the Box?
- The Python solution on this page runs in O(m \times n).
- What is the space complexity of LeetCode 1861. Rotating the Box?
- The Python solution on this page uses O(m \times n) auxiliary space.
- What topics does LeetCode 1861. Rotating the Box cover?
- LeetCode 1861. Rotating the Box is tagged Array, Two Pointers and Matrix on LeetCode.