hi, let Avik connect you.


** You can give your thought about this content and request modifications if needed from Ask For Modifications page. Thank You.

** You can check all the posts on the Posts page.

** More about me in the About Me section.

Rotate Matrix K times


  • Approach:

    1. Initiate an ans array.

    2. For the given matrix, inserted arr[i][j] to ans[i][(j+k)%n].


  • Time and Space Complexity:

      • Time Complexity: O(N*N)

      • Space Complexity: O(N*N)


Code [C++]

#include <bits/stdc++.h>

vector<vector<int>> solve(vector<vector<int>> &arr, int k)

{

int n = arr.size();

// k = k % n;

vector<vector<int>>ans(n, vector<int>(n));

for(int i=0; i<n; i++){

for(int j=0; j<n; j++){

ans[i][(j+k)%n] = arr[i][j];

}

}

return ans;

}