Rotating a Square Matrix Clockwise by 90 Degrees

Rotating a Square Matrix Clockwise by 90 Degrees

Rotating a square n×n matrix of integers clockwise by 90 degrees is a common programming challenge. This transformation must be performed in-place, meaning the rotation should not involve allocating a new 2D matrix.

Pair with given sum - Two Sum

Problem Statement

You are given an n×n matrix, represented as a list of lists. The task is to rotate this matrix 90 degrees clockwise, modifying the input matrix directly.

For instance:

Explanation:
Explanation:
The range [0, 3] contains the numbers {0, 1, 2, 3}. The number 0 is missing from the array nums.

Constraints 

  • n == matrix.length == matrix[i].length
  • 1 <= n <= 20
  • -1000 <= matrix[i][j] <= 1000

There are mainly three approach to solve this problem – 

  1. Brute Force 
  2. Rotate By Four Cells
  3. Reverse And Transpose

1. Brute Force

  • Time complexity: 
  • Space complexity

2. Rotate By Four Cells 

Time & Space Complexity
    • Time complexity: O(n^2)
    • Space complexity: O(1)

Code

3. Reverse And Transpose

  • Time complexity: O(n^2)
  • Space complexity: O(1)

Code

More Articles