Update appNew update is available. Click here to update.
sidenav-btnClose
Topic list
Rotate Matrix
MEDIUM
15 mins
125 upvotes
Matrices (2D Arrays)
Topics (Covered in this problem)
Problem solved
Badge
Skill meter
Matrices (2D Arrays)
-
-
Other topics
Problem solved
Badge
Skill meter
Strings
-
-
Linked List
-
-
Sorting
-
-
Binary Search
-
-
Stacks & Queues
-
-
Trees
-
-
Graph
-
-
Dynamic Programming
-
-
Greedy
-
-
Tries
-
-
Arrays
-
-
SQL
-
-
Binary Search Trees
-
-
Heap
-
-
Bit Manipulation
-
-
Solve problems & track your progress
Checkout your overall progress in every topic here
Become
userLevel
Sensei
in DSA topics
Open the topic and solve more problems associated with it to improve your skills
Check out the skill meter for every topic
See how many problems you are left with to solve for cracking any stage. Score more than zero to get your progress counted.

Rotate Matrix

Contributed by
Ashwani
Medium
yellow-spark
0/80
Avg time to solve 15 mins
Success Rate 85 %
Share
125 upvotes

Problem Statement

Given a 2-dimensional matrix of size ‘N’ x ‘M’, rotate the elements of the matrix clockwise.

For example: 
Input Matrix: [ [ 1, 2, 3 ] 
                [ 4, 5, 6 ] 
                [ 7, 8, 9 ] ]

Output Matrix: [ [ 4, 1, 2 ] 
                 [ 7, 5, 3 ] 
                 [ 8, 9, 6 ] ]

The output matrix is generated by rotating the elements of the input matrix in a clockwise direction. Note that every element is rotated only once. 
Note :
You do not need to print anything; it has already been taken care of. Also, update the given matrix in-place.
Detailed explanation ( Input/output format, Notes, Constraints, Images )
Sample Input 1 :
1
4 4
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Sample Output 1 :
5 1 2 3
9 10 6 4
13 11 7 8
14 15 16 12
Explanation of Sample Input 1 :

The resulting matrix after rotating the given matrix clockwise is shown above. 
Sample Input 2 :
2
2 2
1 3
4 5
3 3
3 4 5
5 6 7
8 10 20
Sample Output 2 :
4 1
5 3
5 3 4
8 6 5
10 20 7 
Reset Code
Full screen
Auto
copy-code
Console