Problem Title : Left Rotate Matrix K times
Dhruva Bhat S N
Passionate Web Developer | Crafting Innovative Solutions with Expertise in Frontend & Backend Technologies | Intern @ Cloud Ambassadors
Problem Statement:
You are given an integer k and matrix mat. Rotate the elements of the given matrix to the left k times and return the resulting matrix.
Example 1 :
Input: k=1, mat=[[1,2,3],[4,5,6],[7,8,9]]
Output:
2 3 1
5 6 4
8 9 7
Explanation: Rotate the matrix by one
1 2 3 2 3 1
4 5 6 => 5 6 4
7 8 9 8 9 7
Example 2 :
Input: k=2, mat=[[1,2,3],[4,5,6],[7,8,9]]
Output:
3 1 2
6 4 5
9 7 8
Explanation: After rotating the matrix looks like
1 2 3 2 3 1 3 1 2
4 5 6 => 5 6 4 => 6 4 5
7 8 9 8 9 7 9 7 8
- Expected Time Complexity: O(N*M)
- Expected Space Complexity: O(N*M)
Constraints:
- 1<= mat.size, mat[0].size, mat[i][j] <=1000
- 1<=k<=10000
Java Code
class Solution {
int[][] rotateMatrix(int k, int mat[][]) {
// code here
int rows= mat.length;
int columns = mat[0].length;
k = k%columns;
for(int i =0; i<rows; i++){
swap(mat[i], 0, k-1);
swap(mat[i], k, columns - 1);
swap(mat[i], 0, columns-1);
}
return mat;
}
void swap(int arr[], int i, int j){
while(i < j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
}
}
Explanation :
Method Signature:
int[][] rotateMatrix(int k, int mat[][])
- Parameters: int k: Number of positions to rotate each row to the right.int[][] mat: The 2D array representing the matrix to be rotated.
- Returns: The rotated matrix.
Initialize Variables:
Copy code
int rows = mat.length;
int columns = mat[0].length;
- rows: The number of rows in the matrix.
- columns: The number of columns in the matrix.
Reduce k to Within Bounds:
k = k % columns;
- This ensures k is within the range of [0, columns - 1].
- Rotating by columns times results in the original row, so this step optimizes unnecessary full rotations.
Rotate Each Row:
for (int i = 0; i < rows; i++) {
swap(mat[i], 0, k - 1);
swap(mat[i], k, columns - 1);
swap(mat[i], 0, columns - 1);
}
- For each row i: First swap: Reverses the first k elements (mat[i][0] to mat[i][k-1]).Second swap: Reverses the remaining elements (mat[i][k] to mat[i][columns-1]).Third swap: Reverses the entire row to complete the right rotation by k positions.
Return the Rotated Matrix:
return mat;
- After processing all rows, the rotated matrix is returned.
Method Signature:
void swap(int arr[], int i, int j)
- Parameters: int arr[]: The array (or row of the matrix) to be manipulated. int i: The starting index of the segment to be reversed. int j: The ending index of the segment to be reversed.
- Returns: Nothing (void).
Reverse the Subarray:
while (i < j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
i++;
j--;
}
- Swaps elements at indices i and j, moving inward towards the center.
- Continues until i is no longer less than j.
- This effectively reverses the segment from i to j in the array.