Skip to main content
Back to problems
#48
Medium Algorithms

Rotate image

Array Math Matrix
79.4% acceptance
Jan 12, 2026
19745
956
You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

Solution

Rust
Time O(n²)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn rotate(matrix: &mut Vec<Vec<i32>>) {
    let n = matrix.len();
    
    // Transpose the matrix (swap matrix[i][j] with matrix[j][i])
    for i in 0..n {
      for j in i+1..n {
        let temp = matrix[i][j];
        matrix[i][j] = matrix[j][i];
        matrix[j][i] = temp;
      }
    }
    
    // Reverse each row to complete the 90-degree clockwise rotation
    for i in 0..n {
      matrix[i].reverse();
    }
  }
}