VOOZH about

URL: https://www.geeksforgeeks.org/dsa/rotate-a-matrix-k-times-clockwise/

⇱ Rotate a Matrix k Times Clockwise - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Rotate a Matrix k Times Clockwise

Last Updated : 23 Jul, 2025

Given a matrix of order m*n and a value k, the task is to rotate each ring of the matrix clockwise by k.

Examples:

Input :k = 3
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

Input : k = 2
1 2 3 4
10 11 12 5
9 8 7 6
Output:
9 10 1 2
8 11 12 3
7 6 5 4

Naive Solution - O(k*m*n) Time and O(1) Space

We simply use the solution of clockwise rotate by one and call it in a loop.


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

Efficient Solution - O(m*n) Time and O(m*n) Space

The idea is to traverse matrix in spiral form. Here is the algorithm to solve this problem : 

  • Make an auxiliary array temp[] of size m*n.
  • Start traversing matrix in spiral form and store elements of current ring in temp[] array. While storing the elements in temp, keep track of starting and ending positions of current ring.
  • For every ring that is being stored in temp[], right rotate that subarray temp[]
  • Repeat this process for each ring of matrix.
  • In last traverse matrix again spirally and copy elements of temp[] array to matrix..

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


Comment
Article Tags:
Article Tags: