The Indian Engineer

Problem 1861 Rotating the Box

Posted on Last edited 4 mins

Array Two-Pointers Matrix

Problem Statement

Link - Problem 1861

Question

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:

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:

Solution

class Solution {
public:
    vector<vector<char>> rotateTheBox(vector<vector<char>>& box) {
        int m =box.size(),n=box[0].size();
        for(auto &row:box){
            int obstacle = row.size();
            for(int i = row.size()-1; i>=0; i--){
                if(row[i]=='#'){
                    char temp = row[i];
                    row[i]='.';
                    row[obstacle-1]=temp;
                    obstacle--;
                }

                if(row[i]=='*')
                    obstacle =i;
            }
        }

        vector<vector<char>>result(n,vector<char>(m,'.'));

        for(int i = 0; i<m; i++)
            for(int j = 0; j<n; j++)
                result[j][m-1-i] = box[i][j];

        return result;
    }
};

Complexity Analysis

Algorithm Time Complexity Space Complexity
Greedy O(mn) O(mn)

Explanation

1. Intuition

2. Implementation


Complexity Analysis

Time Complexity:

Space Complexity: