DDSA Solutions

1861. Rotating the Box

Time: O(mn)
Space: O(mn)

Problem Overview

Rotating the Box (Easy) asks you to solve a structured algorithmic task. This is a common Array / Two Pointers pattern in coding interviews. Simulate gravity rightward per row; then rotate the matrix 90° clockwise.

A full step-by-step explanation is being added. See the study guide for pattern-based practice.

Approach

Simulate gravity rightward per row; then rotate the matrix 90° clockwise.

Related patterns: Array, Two Pointers, Matrix

1861.cs
C#
// Approach: Simulate gravity rightward per row; then rotate the matrix 90° clockwise.
// Time: O(mn) Space: O(mn)

public class Solution
{
    public char[][] RotateTheBox(char[][] box)
    {
        int m = box.Length;
        int n = box[0].Length;
        char[][] ans = new char[n][];
        for (int i = 0; i < n; i++)
        {
            ans[i] = new char[m];
            Array.Fill(ans[i], '.');
        }

        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;
    }
}
Was this solution helpful?

Related Problems