Back to blog
Nov 23, 2024
3 min read

LeetCode 1861: Rotating the Box

Leetcode 1861: Rotating the Box solution in Python

Problem Description

LeetCode Problem 1861

You are given an m x n matrix of characters box 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 box 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: box = [[”#”,”.”,”#”]] Output: [[”.”],   [”#”],   [”#“]]

Example 2:

Input: box = [[”#”,”.”,"",”.”],   [”#”,”#”,"",”.“]] Output: [[”#”,”.”],   [”#”,”#”],   ["",""],   [”.”,”.“]]

Example 3:

Input: box = [[”#”,”#”,"",”.”,"",”.”],   [”#”,”#”,”#”,"",”.”,”.”],   [”#”,”#”,”#”,”.”,”#”,”.“]] Output: [[”.”,”#”,”#”],   [”.”,”#”,”#”],   [”#”,”#”,""],   [”#”,"",”.”],   [”#”,”.”,""],   [”#”,”.”,”.“]]

 

Constraints:

  • m == box.length
  • n == box[i].length
  • 1 <= m, n <= 500
  • box[i][j] is either ’#’, ’*’, or ’.‘.

Difficulty: Medium

Tags: array, two pointers, matrix

Rating: 95.12%

Complexity Analysis

The solution has the following complexity characteristics:

  • Time Complexity: O(n2)O(n²)
  • Space Complexity: O(n2)O(n²)

Note: This is an automated analysis and may not capture all edge cases or specific algorithmic optimizations.

Solution

Here’s my Python solution to this problem:

class Solution:
    def rotateTheBox(self, box: List[List[str]]) -> List[List[str]]:
        m, n = len(box), len(box[0])

        for row in range(m):
            right = n - 1  # rightmost available position
            for col in range(n - 1, -1, -1):
                if box[row][col] == '#':
                    # Stone found, move it to rightmost available position
                    box[row][col] = '.'
                    box[row][right] = '#'
                    right -= 1
                elif box[row][col] == '*':
                    # Obstacle found, update rightmost available position
                    right = col - 1
        
        rotated = [['' for _ in range(m)] for _ in range(n)]
        for i in range(m):
            for j in range(n):
                rotated[j][m-1-i] = box[i][j]
                
        return rotated