Shape Rule
Spiral matrix
Numbers flow clockwise around each border ring — 1..10 on the outer ring of a 10×10 grid, then inward to 100 at the center.

Program 62 generates a perfect square spiral: fill an n×n grid with numbers 1..n² clockwise, layer by layer, using a 2D array and shrinking boundaries. This tutorial covers the spiral fill order, boundary variables, a live preview, worked JavaScript examples, edge cases, and O(n²) complexity.
Spiral matrix
Numbers flow clockwise around each border ring — 1..10 on the outer ring of a 10×10 grid, then inward to 100 at the center.
2D array grid
Array.from({ length: n }, () => Array(n).fill(0)) stores each cell before logging with fixed-width formatting.
low / high
low and high mark the current square ring — increment/decrement after each layer to move inward.
Top, right, bottom, left
Each layer fills top row, right column, bottom row, left column — incrementing counter n each cell.
n = 3..8
Pick grid size and draw the spiral matrix in the browser.
Complexity
Every cell visited once — 10×10 = 100 cells, hence O(n²) time and space.
A perfect square spiral (spiral matrix) fills an n×n grid with consecutive integers flowing clockwise around shrinking border rings. With n = 10, you get a 10×10 grid numbered 1 through 100.
In JavaScript create Array.from({ length: n }, () => Array(n).fill(0)), walk each layer with low/high boundaries, fill four sides per ring, then log with String(value).padStart(4, " ") fixed-width formatting.
Spiral-matrix logic appears in interviews, grid simulations, and image processing — it bridges simple loops to 2D array reasoning.
Array.from({ length: n }, () => Array(n).fill(0)) stores the grid.
low/high track each ring.
Program 61 works on one number; Program 62 fills a 2D grid.
Last number pattern — continue to JavaScript Star Patterns next.
In short: create a 2D array, fill four sides per layer with shrinking boundaries, log with String(value).padStart(4, " ").
Given grid size n = 10, fill an n×n array with numbers 1..n² in a clockwise spiral starting from the top-left corner.
// n = 4 (compact sample)
// 1 2 3 4
//12 13 14 5
//11 16 15 6
//10 9 8 7 | Item | Type | Description |
|---|---|---|
n | number | Grid dimension — 10 in the fixed demo (10×10 = 100 cells). |
arr[i,j] | 2D array | 2D array storing each cell value. |
low, high | number | Current layer boundaries — start 0 and n−1, move inward each ring. |
| Fill counter | number | Starts at 1, increments for every cell placed. |
| Layers | number | n/2 rings for even n — 5 layers when n = 10. |
| Log format | string | String(value).padStart(4, " ") fixed width keeps columns aligned. |
create n×n array
set low=0, high=n-1, val=1
while low <= high:
fill top row left→right
fill right column top→bottom
fill bottom row right→left
fill left column bottom→top
low++, high--
print array with fixed width | Approach | Idea | Best for |
|---|---|---|
| low / high rings | Outer loop over layers, four inner loops per side | Fixed 10×10 demo (Example 1) |
| top/bottom/left/right | While loop shrinks all four boundaries | Configurable size (Example 2) |
| Compact trace | n = 4 on paper first | Quick dry-runs |
| Direction array | Simulate walk with dx/dy turns | Alternative interview solution |
| Wider print width | {0, 5} or more when n² > 9999 | Large grids |
| Goal | Pattern |
|---|---|
| Allocate | Array.from({ length: n }, () => Array(n).fill(0)) |
| Layer loop | for (i = 0; i < n/2; i++, low++, high--) |
| Fill order | Top row → right col → bottom row → left col |
| Print cell | String(arr[i][j]).padStart(4, " ") |
Same spiral matrix — three ways to set grid size and trace the fill logic.
n = 10Hard-coded with low/high rings
top/bottom/left/rightConfigurable n from console
n = 4Quick dry-run on paper
4 per layerTop, right, bottom, left
padStart(4)Fixed-width columns
Reach for this pattern when teaching 2D arrays, boundary control, and O(n²) grid algorithms in JavaScript.
Natural finale for the number-pattern series — graduate from 1D loops to 2D spiral filling.
Classic spiral-matrix question — explain boundary shrinking before coding.
Index reasoning with arr[row, col] and nested loop bounds.
Continue to C star-pattern programs after mastering this grid exercise.
Very large grids produce huge console output — cap n for demos.
Key benefit: one program that locks in 2D arrays, boundary control, and O(n²) grid thinking.
Enter grid size between 3 and 8 and draw the perfect square spiral matrix in the browser.
Three complete JavaScript programs — fixed 10×10 spiral, configurable size with four boundaries, and a compact 4×4 trace. Click View Output to reveal sample console results.
Generate a 10×10 perfect square spiral with low/high boundary rings.
Hard-coded grid — fill each layer top, right, bottom, left, then log with width 4.
const n = 10;
const arr = Array.from({ length: n }, () => Array(n).fill(0));
let low = 0;
let high = n - 1;
let val = 1;
for (let i = 0; i < Math.floor(n / 2); i++) {
for (let j = low; j <= high; j++) {
arr[i][j] = val;
val++;
}
for (let j = low + 1; j <= high; j++) {
arr[j][high] = val;
val++;
}
for (let j = high - 1; j >= low; j--) {
arr[high][j] = val;
val++;
}
for (let j = high - 1; j > low; j--) {
arr[j][low] = val;
val++;
}
low++;
high--;
}
console.log("Perfect Square Spiral\\n");
for (const row of arr) {
let line = "";
for (const cell of row) {
line += String(cell).padStart(4, " ");
}
console.log(line);
} Five layers fill the 10×10 grid — outer loop runs i = 0..4, each iteration walks four sides and moves boundaries inward.
Read grid size n from the user and fill with top/bottom/left/right boundaries.
Configurable n×n spiral using a while loop and four boundary variables.
const nInput = prompt("Enter size n:");
const n = parseInt(nInput, 10);
if (!Number.isFinite(n) || n <= 0) {
console.log("Please enter a positive integer.");
} else {
const a = Array.from({ length: n }, () => Array(n).fill(0));
let top = 0;
let bottom = n - 1;
let left = 0;
let right = n - 1;
let val = 1;
while (top <= bottom && left <= right) {
for (let j = left; j <= right; j++) {
a[top][j] = val;
val++;
}
top++;
for (let i = top; i <= bottom; i++) {
a[i][right] = val;
val++;
}
right--;
if (top <= bottom) {
for (let j = right; j >= left; j--) {
a[bottom][j] = val;
val++;
}
bottom--;
}
if (left <= right) {
for (let i = bottom; i >= top; i--) {
a[i][left] = val;
val++;
}
left++;
}
}
for (const row of a) {
let line = "";
for (const cell of row) {
line += String(cell).padStart(4, " ");
}
console.log(line);
}
} The while loop shrinks all four boundaries after each side fill — works for any positive n, odd or even.
Use n = 4 for a quick paper trace before larger grids.
Same boundary approach with a small grid — easy to dry-run on paper.
const n = 4;
const a = Array.from({ length: n }, () => Array(n).fill(0));
let top = 0;
let bottom = n - 1;
let left = 0;
let right = n - 1;
let val = 1;
while (top <= bottom && left <= right) {
for (let j = left; j <= right; j++) {
a[top][j] = val;
val++;
}
top++;
for (let i = top; i <= bottom; i++) {
a[i][right] = val;
val++;
}
right--;
if (top <= bottom) {
for (let j = right; j >= left; j--) {
a[bottom][j] = val;
val++;
}
bottom--;
}
if (left <= right) {
for (let i = bottom; i >= top; i--) {
a[i][left] = val;
val++;
}
left++;
}
}
for (const row of a) {
let line = "";
for (const cell of row) {
line += String(cell).padStart(4, " ");
}
console.log(line);
} Two layers fill the 4×4 grid — trace values 1–16 clockwise on paper before scaling to 10×10.
Array.from({ length: n }, () => Array(n).fill(0)) holds all spiral values before logging.
low = 0, high = n - 1 (or top/bottom/left/right) mark the current ring.
Top row, right column, bottom row, left column — incrementing counter each cell.
String(arr[i][j]).padStart(4, " ") keeps columns aligned.
n² cells filled and logged — O(n²) time and space.
n = 4Trace the first (outer) ring of a 4×4 spiral — values 1 through 12 on the border, then inner 2×2 fills 13–16.
| Side | Cells filled | Values placed |
|---|---|---|
| Top row | (0,0)..(0,3) | 1, 2, 3, 4 |
| Right column | (1,3)..(3,3) | 5, 6, 7 |
| Bottom row | (3,2)..(3,0) | 8, 9, 10 |
| Left column | (2,0)..(1,0) | 11, 12 |
| Inner 2×2 | Second layer | 13, 14, 15, 16 |
For n = 10, repeat this four-side pattern for 5 concentric rings until the center cell holds 100.
Where spiral-matrix filling shows up beyond the homework prompt.
Array.from({ length: n }, () => Array(n).fill(0)) with row/column indexing — a visual grid exercise for beginners.
Example: trace which cells get values 1–4 on the outer ring of a 4×4 grid.
Classic spiral-matrix question — explain boundary shrinking before coding.
Example: walk through top → right → bottom → left for one layer.
Final number-pattern program — graduates from 1D loops to 2D boundary control.
Example: compare Program 61’s while loop with nested spiral loops here.
After mastering grids, move to C star-pattern programs for shape-based output.
Example: continue to JavaScript Star Patterns next.
Every cell visited once — concrete quadratic complexity for grid algorithms.
Example: 10×10 = 100 cells filled and printed.
Spiral traversal appears in image processing, maze generation, and game maps.
Example: adapt the fill order to visit cells in spiral order without storing all values.
Pro Tip: dry-run a 4×4 grid on paper before attempting 10×10 — the four-side pattern repeats per layer.
Why spiral-matrix exercises belong in every beginner JavaScript course.
Students see numbers flow around the grid — wrong boundary logic shows up immediately.
Four inner loops per layer reinforce index bounds and loop direction (forward/backward).
Spiral matrix is a standard coding question — this tutorial maps directly to it.
Same boundary approach works for odd and even sizes — only print width may need adjustment.
Pro Tip: trace the first layer of n = 4 on paper — values 1–12 on the border before the inner 2×2 fills 13–16.
Small habits that keep spiral-matrix code clean.
Top → right → bottom → left — skipping or reordering breaks the spiral.
Start right column at low + 1, bottom row at high - 1 — corners are already filled.
String(value).padStart(4, " ") keeps columns aligned for n up to 10×10.
When using top/bottom/left/right, check top <= bottom before bottom and left fills.
Dry-run a 4×4 grid on paper before coding the 10×10 demo.
Pro Tip: if numbers jump or repeat, check whether a side loop includes an already-filled corner cell.
Mistakes that commonly break spiral-matrix programs.
Starting every side at the same corner overwrites cells — spiral breaks at turns.
→ Skip the first cell on right, bottom, and left sides after the top row.
Running too many or too few outer iterations leaves cells empty or overwritten.
→ Use n/2 layers for even n — 5 rings when n = 10.
On odd n or the last layer, bottom/left fills may run when boundaries crossed.
→ Wrap bottom and left fills with if (top <= bottom) checks.
Printing without fixed width makes large numbers shift columns.
→ Use String(value).padStart(4, " ") or wider when n² exceeds 9999.
Swapping arr[i,j] indices fills transposed or scrambled output.
→ Top row uses fixed row i, varying column j.
Check these inputs before calling the solution done.
Grid holds only value 1 — one layer, one print.
Four cells in one layer — good minimal test case.
Center cell 9 filled in the innermost layer — verify boundary guards.
Reject with a message — do not create a grid when n <= 0.
Bare parseInt(prompt()) returns NaN — validate with Number.isFinite.
Cap n for demos — O(n²) cells means O(n²) print lines.
Try these variations to lock in the spiral pattern.
low++ and high-- after four sides.Quick Takeaway: create a 2D array, fill four sides per layer, tighten boundaries, log with String(value).padStart(4, " ").
| Program | Time | Extra space |
|---|---|---|
| Fixed 10×10 (Example 1) | O(n²) — n = 10, 100 cells | O(n²) for the array |
| User input (Example 2) | O(n²) | O(n²) |
| Compact 4×4 (Example 3) | O(n²) — n = 4, 16 cells | O(n²) |
The perfect square spiral is a capstone 2D-array exercise: boundary control, four-side fills, and O(n²) grid thinking. Master the fixed 10×10 version, then try user input with configurable n and the compact 4×4 trace.
Practice the three examples above, then continue to JavaScript Star Patterns — the next chapter after number patterns.
Fill top → right → bottom → left per layer, tighten boundaries, log with fixed width — validate n when reading from prompt().
String(value).padStart(4, " ") for aligned columnsarr[i,j]n > 0Print the perfect square spiral the beginner-friendly way.
Fill clockwise per layer
Definition2D array stores grid
StructureTop, right, bottom, left
Orderlow/high shrink inward
ControlO(n²) time & space
AnalysisA perfect square spiral fills an n×n grid with numbers 1..n² by walking each border layer clockwise and tightening low/high boundaries — runtime is O(n²).
Number patterns complete — move on to star-shaped output programs.
12 people found this page helpful