easy +10 pts

Rotate Image 90 Degrees Clockwise

Rotate a square matrix 90 degrees clockwise in-place or return a new matrix.

Write a function `rotate_image(matrix)` that takes a square matrix (list of lists) and rotates it 90 degrees clockwise. The function should return the rotated matrix. You may modify the input matrix or create a new one, but the returned matrix must have the rotated values. For example, rotating `[[1, 2], [3, 4]]` clockwise gives `[[3, 1], [4, 2]]`.

Constraints

- The input is a square matrix (n x n) with `1 <= n <= 100`. - Elements can be any integers. - The matrix is non-empty. - Time complexity: O(n^2), space complexity: O(1) if in-place, otherwise O(n^2).

Example

>>> rotate_image([[1, 2], [3, 4]])
[[3, 1], [4, 2]]
>>> rotate_image([[1]])
[[1]]
>>> rotate_image([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
[[7, 4, 1], [8, 5, 2], [9, 6, 3]]
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Think about how each element moves: row i, column j goes to row j, column n-1-i.
You can first transpose the matrix (swap rows and columns), then reverse each row.
Alternatively, create a new matrix and fill it using the index mapping.
For a 2x2 matrix, the corners swap in a cycle.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.