Skip to content

Commit ce8fdc3

Browse files
committed
Add week 14 solutions: spiralMatrix
1 parent c21881f commit ce8fdc3

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

spiral-matrix/yolophg.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
// Time Complexity: O(m*n) m = number of rows, n = number of cols
2+
// Space Complexity: O(m*n)
3+
4+
var spiralOrder = function (matrix) {
5+
let result = [];
6+
7+
while (matrix.length > 0) {
8+
// add the first row to the result
9+
result = result.concat(matrix.shift());
10+
11+
// add the last element of each remaining row to the result
12+
for (let i = 0; i < matrix.length; i++) {
13+
if (matrix[i].length > 0) {
14+
result.push(matrix[i].pop());
15+
}
16+
}
17+
18+
// add the last row in reverse order to the result, if any rows are left
19+
if (matrix.length > 0) {
20+
result = result.concat(matrix.pop().reverse());
21+
}
22+
23+
// add the first element of each remaining row to the result in reverse order
24+
for (let i = matrix.length - 1; i >= 0; i--) {
25+
if (matrix[i].length > 0) {
26+
result.push(matrix[i].shift());
27+
}
28+
}
29+
}
30+
31+
// return the result array containing the elements in spiral order
32+
return result;
33+
};

0 commit comments

Comments
 (0)