This is one interesting interview question.
Generally, we know the matrix of any size but what is special about Spiral here.
2 * 2 Matrix can be:
[[1,2],
[3,4]]
So, it spiral version is:
[[1,2],
[4,3]]
3 * 3 Matrix can be:
[[1,2,3],
[4,5,6],
[7,8,9]]
So, it's spiral version is:
[[1,2,3],
[8,9,4],
[7,6,5]]
An image can explain better rather much long theories. I tried it using below image.
Ok. Now, I implemented this using javascript.
Here, is the code:
function spiralMatrix(n) {
const arr = Array.from({ length: n }, () => []);
let row = 0;
let col = 0;
let rowEnd = n - 1;
let colEnd = n - 1;
let counter = 1;
while (col <= colEnd && row <= rowEnd) {
// Top row & middle value (Where col === colEnd && row === rowEnd)
for (let i = col; i <= colEnd; i++) {
arr[row][i] = counter;
counter++;
}
row++;
// end column
for (let i = row; i <= rowEnd; i++) {
arr[i][colEnd] = counter;
counter++;
}
colEnd--;
// end row
for (let i = colEnd; i >= col; i--) {
arr[rowEnd][i] = counter;
counter++;
}
rowEnd--;
// First col from end
for (let i = rowEnd; i >= row; i--) {
arr[i][col] = counter;
counter++;
}
col++;
}
return arr;
}
I would love to explain how I achieved it.
Here is the GIF that makes you get the Pseudo code behind this code.
Meanwhile, If some expert came across this article. Please do minify the above code.
Thanks.
π Love to see your response
- Like - You reached here means. I think, I deserve a like.
- Comment - We can learn together.
- Share - Makes others also find this resource useful.
- Subscribe / Follow - to stay up to date with my daily articles.
- Encourage me - You can buy me a Coffee
Let's discuss further.
- Just DM @urstrulyvishwak
-
Or mention
@urstrulyvishwak
Top comments (6)
This seems to work as well
Though the arrays are going to be the holey rather than the packed kind.
This is pretty cool. I've never heard of this algorithm before, what can it be used for?
Deliberate Learning
Interesting. I've never been able to articulate that before.
Typical leetcode question
thanks