25(June) Left Rotate Matrix K times
25. Left Rotate Matrix K times
The problem can be found at the following link: Question Link
Problem Description
You are given an integer k and a matrix mat. Return a matrix where it is rotated left k times.
Example:
Input:
k = 1
mat = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]Output:
2 3 1
5 6 4
8 9 7Explanation: After rotating the matrix by one position to the left, it becomes:
2 3 1
5 6 4
8 9 7My Approach
Initialization:
Determine the number of rows (
n) and columns (m) in the matrixmat.Create a new matrix
ansof the same dimensions to store the result after rotation.
Rotation Calculation:
Calculate the effective number of rotations needed using
k % mto handle cases wherekis larger thanm.Iterate over each element in the original matrix
mat, and determine its new position in the matrixansafter rotation.
Return:
Return the matrix
anscontaining the elements afterkleft rotations.
Time and Auxiliary Space Complexity
Expected Time Complexity: O(n * m), as we iterate over all elements in the matrix once.
Expected Auxiliary Space Complexity: O(n * m), as we use an additional matrix of the same size to store the rotated elements.
Code (C++)
Code (Java)
Code (Python)
Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!
⭐ If you find this helpful, please give this repository a star! ⭐
📍Visitor Count
Last updated