CSInterviewing
Problems
Register
Login
Problems
Register
Login
menu
Rotate Image (Matrix 90°)
matrix
array
# Rotate Image (Matrix 90°) ## Difficulty Medium ## Tags `matrix`, `array` ## Problem Statement You are given an `n x n` 2D matrix representing an image. Rotate the image by 90 degrees clockwise **in-place**. You must modify the input matrix directly. DO NOT allocate another 2D matrix. ## Constraints - n == matrix.length == matrix[i].length - 1 ≤ n ≤ 20 - -1000 ≤ matrix[i][j] ≤ 1000 ## Signatures ### Python ```python def rotate(matrix: List[List[int]]) -> None: pass ``` ### Java ```java public class Solution { public void rotate(List<List<Integer>> matrix) { return null; } } ``` ### Csharp ```csharp public class Solution { public void rotate(IList<IList<int>> matrix) { throw new NotImplementedException(); } } ``` ### Cpp ```cpp class Solution { public: void rotate(vector<vector<int>> matrix) { } }; ``` ### C ```c void rotate(vector<int*> matrix) { } ``` ### Ruby ```ruby def rotate(matrix) end ``` ### Perl ```perl sub rotate { my ($self, @args) = @_; } ``` ### Scala ```scala object Solution { def rotate(matrix: List[List[Int]]): Unit = { } } ``` ### Haskell ```haskell rotate :: ... -> ... rotate args = undefined ``` ### Clojure ```clojure (defn rotate [matrix] ) ``` ### Scheme ```scheme (define (rotate matrix) ) ``` ## Examples ### Example 1 **Input:** ``` matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] ``` **Output:** ``` [ [7, 4, 1], [8, 5, 2], [9, 6, 3] ] ``` ### Example 2 **Input:** ``` matrix = [ [5, 1, 9, 11], [2, 4, 8, 10], [13, 3, 6, 7], [15, 14, 12, 16] ] ``` **Output:** ``` [ [15, 13, 2, 5], [14, 3, 4, 1], [12, 6, 8, 9], [16, 7, 10, 11] ] ``` ### Example 3 **Input:** ``` matrix = [[1]] ``` **Output:** ``` [[1]] ``` ## Hints 1. **Method 1**: Transpose the matrix, then reverse each row. - Transpose: swap matrix[i][j] with matrix[j][i] - Reverse each row 2. **Method 2**: Rotate layer by layer (ring by ring). - For each layer, perform a 4-way swap of elements.
Login required
Please log in to view the solution editor and submit code.
Login
Register