FastPrepRotate a Square Grid Clockwise

Rotate a Square Grid Clockwise

C3.ai logoC3.ai● MediumNEW GRADONSITE INTERVIEW

Updated

Problem statement

You are given a square grid of integers, grid, with n rows and n columns.

Turn the grid a quarter turn clockwise (90 degrees to the right) and return the turned grid. After the turn, the first column read from bottom to top becomes the first row, the second column read from bottom to top becomes the second row, and so on.

You may build a new grid or change grid itself and return it. Doing it in place, with only a few extra variables, is a good follow-up.

Function

rotateClockwise(grid: int[][]) → int[][]

Examples

Example 1

grid = [[6,1],[3,8]]return = [[3,6],[8,1]]
grid
01061138
return
01036181
Moved or new

Turning the grid a quarter turn to the right moves the left column, read from bottom to top (3, 6), into the top row. The right column, read from bottom to top (8, 1), becomes the bottom row.

Example 2

grid = [[5,-1,0],[7,8,2],[-4,6,9]]return = [[-4,7,5],[6,8,-1],[9,2,0]]
grid
01205-1017822-469
return
0120-475168-12920
Moved or new

The first column read from bottom to top is -4, 7, 5, so that is the new first row. The second column from bottom to top is 6, 8, -1, and the third is 9, 2, 0. The center value 8 stays in place.

Example 3

grid = [[-7]]return = [[-7]]
grid
00-7
return
00-7

A grid with one cell looks the same after any turn.

Constraints

  • 1 <= n <= 25, where n == grid.length == grid[i].length
  • -1000 <= grid[i][j] <= 1000

More C3.ai interview questions

Similar questions at other companies

Interview reports that mention this question

C3.ai interview experiences

All C3.ai interview questionsSee C3.ai hiring insights
Saved
class Solution {
    public int[][] rotateClockwise(int[][] grid) {
        // Write your code here.
    }
}
Checking account…