Skip to content

1861. Rotating the Box 👍

  • Time: $O(mn)$
  • Space: $O(mn)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
 public:
  vector<vector<char>> rotateTheBox(vector<vector<char>>& box) {
    const int m = box.size();
    const int n = box[0].size();
    vector<vector<char>> ans(n, vector<char>(m, '.'));

    for (int i = 0; i < m; ++i)
      for (int j = n - 1, k = n - 1; j >= 0; --j)
        if (box[i][j] != '.') {
          if (box[i][j] == '*')
            k = j;
          ans[k--][m - i - 1] = box[i][j];
        }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Solution {
  public char[][] rotateTheBox(char[][] box) {
    final int m = box.length;
    final int n = box[0].length;
    char[][] ans = new char[n][m];
    Arrays.stream(ans).forEach(A -> Arrays.fill(A, '.'));

    for (int i = 0; i < m; ++i)
      for (int j = n - 1, k = n - 1; j >= 0; --j)
        if (box[i][j] != '.') {
          if (box[i][j] == '*')
            k = j;
          ans[k--][m - i - 1] = box[i][j];
        }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
  def rotateTheBox(self, box: list[list[str]]) -> list[list[str]]:
    m = len(box)
    n = len(box[0])
    rotated = [['.'] * m for _ in range(n)]

    for i in range(m):
      k = n - 1
      for j in reversed(range(n)):
        if box[i][j] != '.':
          if box[i][j] == '*':
            k = j
          rotated[k][m - i - 1] = box[i][j]
          k -= 1

    return [''.join(row) for row in rotated]