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.
// 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.
// 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],
// ]
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).matrix must be exactly what they passed in. (True in-place O(1)-space rotation is a separate exercise — covered in Going further.)1×1 case returns a fresh array rather than the original reference.