Rotate Image

Medium#48rotate

You get a square n × n matrix, a picture. Turn it 90° clockwise in place: change the matrix itself, without a second one. Our example: the letters ABCD EFGH IJKL MNOP, row by row. After the turn it reads MIEA NJFB OKGC PLHD: the left column, read from the bottom up, has become the top row.

input
matrix: an n × n square of integers, an image.
returns
Nothing: turn matrix 90° clockwise in place, so that its first row is its first column read from the bottom up. Change the given matrix; do not make another one.
constraints
  • 1 ≤ n ≤ 20, matrix[i].length = n
  • −1000 ≤ matrix[i][j] ≤ 1000
our 11 tests keep to them
examples
Open a test in the tests panel: it shows the input and the expected answer.
/**
 * @param {number[][]} matrix
 * @return {void} Do not return anything, modify matrix in-place instead.
 */
function rotate(matrix) {

}
Ctrl ↵
format
reset

saved in this browser

11 tests · limit 3 s

Stuck?

See the solution run step by step on our example, then why it works and its complexity.

Watch the walkthrough →

Next: more matrix traversal problems

Pattern “Matrix traversal” →

The problem and its statement belong to LeetCode. Here are our own retelling, example and solution. Patterns Hero is not affiliated with LeetCode.