DDSA Solutions

Left Rotate Matrix K times

Time: O(n*m)
Space: O(n*m)
Advertisement

Intuition

Left rotate each row of matrix by k positions. Use modulo to handle k > cols.

Algorithm

  1. 1For each row: new_row[i] = old_row[(i+k) % n].

Common Pitfalls

  • Rotate left by k = rotate right by (n-k). Build new array or use reversal trick.
Left Rotate Matrix K times.java
Java
// Approach: Normalize k = k % cols. Slice and rearrange each row to simulate left circular rotation.
// Time: O(n*m) Space: O(n*m)
class Solution {
    int[][] rotateMatrix(int k, int mat[][]) {
        int n = mat.length;
        int m = mat[0].length;

        int[][] ans = new int[n][m];

        k = k % m;

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++)
                ans[i][j] = mat[i][(j + k) % m];
        }

        return ans;
    }
}
Advertisement
Was this solution helpful?