Finished
88 * @returns {number[][]}
99 */
1010export const spiralMatrix = (size) => {
11 throw new Error('Remove this line and implement the function');
11 // Edge Case: size 0 or negative size
12 if (size <= 0) {
13 return [];
14 }
15
16 // Edge Case: size 1 matrix
17 if (size === 1) {
18 return [[1]];
19 }
20
21 // Create an empty matrix filled with zeros
22 const matrix = Array(size).fill().map(() => Array(size).fill(0));
23
24 let counter = 1;
25 let startRow = 0;
26 let endRow = size - 1;
27 let startCol = 0;
28 let endCol = size - 1;
29
30 while (startRow <= endRow && startCol <= endCol) {
31 // Top row: left to right
32 for (let i = startCol; i <= endCol; i++) {
33 matrix[startRow][i] = counter++;
34 }
35 startRow++;
36
37 // Right column: top to bottom
38 for (let i = startRow; i <= endRow; i++) {
39 matrix[i][endCol] = counter++;
40 }
41 endCol--;
42
43 // Bottom row: right to left (if there's still a row to fill)
44 if (startRow <= endRow) {
45 for (let i = endCol; i >= startCol; i--) {
46 matrix[endRow][i] = counter++;
47 }
48 endRow--;
49 }
50
51 // Left column: bottom to top (if there's still a column to fill)
52 if (startCol <= endCol) {
53 for (let i = endRow; i >= startRow; i--) {
54 matrix[i][startCol] = counter++;
55 }
56 startCol++;
57 }
58 }
59
60 return matrix;
1261};
62
63// Handled Edge Cases: size 0 or negative size, size 1 matrix
Test NameStatus
empty spiral
Pass
trivial spiral
Pass
spiral of size 2
Pass
spiral of size 3
Pass
spiral of size 4
Pass
spiral of size 5
Pass

© 2025 Ridges AI. Building the future of decentralized AI development.