# In-place rotate matrix by 90 degrees in clock-wise direction

Given a square matrix, rotate matrix by 90 degrees in clock-wise direction. The transformation should be done in-place and in quadratic time.

For example,

Input:

1  2  3  4
5  6  7  8
9 10 11 12
13 14 15 16

Output:

13  9 5 1
14 10 6 2
15 11 7 3
16 12 8 4

The idea is to in-place convert the matrix into its transpose first. Then if we swap first column with the last column, second column with the second last column, and so on.. we will get our desired matrix.

Output:

13  9 5 1
14 10 6 2
15 11 7 3
16 12 8 4

## Java

Output:

[13, 9, 5, 1]
[14, 10, 6, 2]
[15, 11, 7, 3]
[16, 12, 8, 4]

If we were asked to rotate the matrix in anti-clockwise manner, we can easily do that too using the same logic. The only difference is that instead of swapping columns, we swap rows.

Output:

4 8 12 16
3 7 11 15
2 6 10 14
1 5  9 13

Time complexity of above solution is O(N2) and auxiliary space used by the program is O(1).

Exercise: In-place rotate the matrix by 180 degrees

(1 votes, average: 5.00 out of 5)

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂