Matrix Rotation in JavaScript
How to rotate a 2x2 matrix in javascript
Velu S Gautam1 min readInterviews
Rotating a matrix in clock wise direction using for loops.
This question was asked in live coding round of Frontend developer interviews in Flipkart, Walmartlabs
JAVASCRIPT
function rotateMatrix(matrix) {
// Input validation
if (!matrix || !Array.isArray(matrix) || matrix.length === 0) {
return [];
}
const n = matrix.length;
const m = matrix[0].length;
if (!matrix.every(row => typeof row === 'string' && row.length === m)) {
return []; // Ensure all rows are strings of the same length
}
if (m === 1) {
return [matrix.reverse().join('')];
}
// Initialize result array
const result = Array(m).fill('');
// Concatenate characters column-wise in reverse row order
for (let j = 0; j < m; j++) {
for (let i = n - 1; i >= 0; i--) {
result[j] += matrix[i][j];
}
}
return result;
}
console.log(
rotateMatrix([
'.........',
'.##......',
'..###....',
'...###...',
'.....###.',
'......###',
'.....###.',
'...###...',
'..###....',
'.##......',
'.........',
])
);
console.log(rotateMatrix(["a","b","c","d"])) // ["dcba"]Overall Time Complexity
-
General case: O(n × m)
-
Single-column case: O(n).
-
Since the function handles both cases, the worst-case time complexity is O(n × m), where n is the number of rows and m is the number of columns.