Matrix RotationLoading saved progress…

Matrix Rotation

You're given an n×n grid of values — think of it as the pixels of a square image. Implement matrixRotation(matrix), which rotates the grid 90 degrees clockwise and returns the rotated grid as a new 2D array. This is the operation behind the "rotate" button in a photo app: every cell moves to where it would land if you turned the whole picture a quarter-turn to the right. The input must be left untouched.

Signature

// matrix: number[][] — a square (n×n) 2D array. Rows and columns are equal in length.
// returns: number[][] — a NEW n×n 2D array, rotated 90° clockwise.
//   The input `matrix` is NOT modified.
function matrixRotation(matrix): number[][];

After a clockwise rotation, the cell at matrix[i][j] ends up at result[j][n-1-i]. Equivalently, the first row of the result is the first column of the input read bottom-to-top.

Examples

// 3×3 — the top row (1, 2, 3) becomes the right-hand column, top to bottom.
matrixRotation([
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9],
]);
// → [
//     [7, 4, 1],
//     [8, 5, 2],
//     [9, 6, 3],
//   ]
// 2×2 — the smallest non-trivial case.
matrixRotation([
  [1, 2],
  [3, 4],
]);
// → [
//     [3, 1],
//     [4, 2],
//   ]

Notes

  • Square only. The input is always n×n. You don't need to handle rectangular (m×n, m ≠ n) matrices — a rectangular rotation would change the dimensions, which is out of scope here (see the solution's Going further).
  • Clockwise, not counter-clockwise. A clockwise quarter-turn sends the top edge to the right edge. Getting the direction backwards is the single most common mistake — the examples above pin down which way is correct.
  • Do not mutate the input. Return a brand-new 2D array. After the call, the caller's matrix must be exactly what they passed in. (True in-place O(1)-space rotation is a separate exercise — covered in Going further.)
  • Return a new array. Even the 1×1 case returns a fresh array rather than the original reference.
  • Values are opaque. Cells may be any value (positive, negative, zero, even strings). You move them; you never inspect or transform them.
Loading editor…