Arrays and Hashing Walking a matrix

84. Rotate Image

Medium

You are given a square grid of integers matrix with n rows and n columns. Rotate the grid a quarter turn clockwise and return it.

After the turn, the top row of the grid has become its right column, read from top to bottom. The right column has become the bottom row, read from right to left, and the other two sides move the same way. Every cell inside the grid turns with them.

Do it in place: change matrix itself and use only O(1) extra memory. Return matrix at the end.

Example 1

38-10726-45
matrix
603-47852-1
output

Input: matrix = [[3, 8, -1], [0, 7, 2], [6, -4, 5]]

Output: [[6,0,3],[-4,7,8],[5,2,-1]]

Explanation: The old top row 3, 8, −1 is now the right column, from top to bottom. The old left column, read from the bottom up, is 6, 0, 3, and it is now the top row. The centre value 7 stays where it is.

Example 2

12345678910111213141516
matrix
13951141062151173161284
output

Input: matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]

Output: [[13,9,5,1],[14,10,6,2],[15,11,7,3],[16,12,8,4]]

Explanation: Each corner moves to the next corner clockwise: 1 goes from the top-left to the top-right, and 13 goes from the bottom-left to the top-left. The inner 2 × 2 block turns the same way.

Example 3

−10⁹
matrix
−10⁹
output

Input: matrix = [[-1000000000]]

Output: [[-1000000000]]

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

Check your understanding

Work out the answer for this input before you write any code.

matrix = [[1, 2], [3, 4]]

Constraints

  • n == matrix.length == matrix[i].length
  • 1 ≤ n ≤ 300
  • -109 ≤ matrix[i][j] ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.