CodeSignal Interview – rotateImage
https://app.codesignal.com/interview-practice/question/5A8jwLGcEpTPyyjTB/description
Problem
Note: Try to solve this task in-place (with O(1)
additional memory), since this is what you’ll be asked to do during an interview.
You are given an n x n 2D matrix that represents an image. Rotate the image by 90 degrees (clockwise).
Example
For
a = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
the output should be
solution(a) =
[[7, 4, 1],
[8, 5, 2],
[9, 6, 3]]
Solution
Idea
I went the wrong way solving this problem. I tried to find a formula to calculate the new position of an element in the input array. However, after observing a little more, it turned out to be much more simple than that. When we rotate the array 90 degree clockwise:
- The n-th row become the 1st column
- The (n-1)th row become the 2nd column
- ….
- The first row become the n-th column
It’s a piece of cake now.
Code
function solution(a) {
let newArr = [];
// start from the last row to the first row
for (let i = a.length - 1; i >= 0; i--) {
const row = a[i];
for (let j = 0; j < row.length; j++) {
if (i === a.length - 1) {
newArr.push([]);
}
newArr[j].push(row[j]);
}
}
return newArr;
}