JavaScript Program to Print Diamond Pattern
for loops to print spaces and stars in the right order, like this: for(let i=1; i<=n; i++){ console.log(' '.repeat(n-i) + '*'.repeat(2*i-1)); } for(let i=n-1; i>0; i--){ console.log(' '.repeat(n-i) + '*'.repeat(2*i-1)); }.Examples
How to Think About It
Algorithm
Code
const n = 5; for(let i = 1; i <= n; i++) { console.log(' '.repeat(n - i) + '*'.repeat(2 * i - 1)); } for(let i = n - 1; i > 0; i--) { console.log(' '.repeat(n - i) + '*'.repeat(2 * i - 1)); }
Dry Run
Let's trace n=3 through the code to see how the diamond is printed.
Top half line 1
i=1, spaces = 3-1=2, stars = 2*1-1=1, line = ' *'
Top half line 2
i=2, spaces = 3-2=1, stars = 3, line = ' ***'
Top half line 3
i=3, spaces = 3-3=0, stars = 5, line = '*****'
Bottom half line 1
i=2, spaces = 3-2=1, stars = 3, line = ' ***'
Bottom half line 2
i=1, spaces = 3-1=2, stars = 1, line = ' *'
| Line | Spaces | Stars | Output |
|---|---|---|---|
| 1 | 2 | 1 | * |
| 2 | 1 | 3 | *** |
| 3 | 0 | 5 | ***** |
| 4 | 1 | 3 | *** |
| 5 | 2 | 1 | * |
Why This Works
Step 1: Print top half
The first loop prints lines with increasing stars and decreasing spaces using repeat to create the pattern.
Step 2: Print bottom half
The second loop prints lines with decreasing stars and increasing spaces to complete the diamond shape.
Step 3: Use of string repeat
Using ' '.repeat() and '*'.repeat() makes it easy to print the exact number of spaces and stars needed.
Alternative Approaches
let i = 1; while(i <= n) { console.log(' '.repeat(n - i) + '*'.repeat(2 * i - 1)); i++; } i = n - 1; while(i > 0) { console.log(' '.repeat(n - i) + '*'.repeat(2 * i - 1)); i--; }
function printDiamond(n, i = 1) { if(i > n) return; console.log(' '.repeat(n - i) + '*'.repeat(2 * i - 1)); printDiamond(n, i + 1); if(i < n) console.log(' '.repeat(n - i) + '*'.repeat(2 * i - 1)); } printDiamond(5);
Complexity: O(n^2) time, O(1) space
Time Complexity
The program uses two loops each running up to n, and inside each loop it prints up to 2*n characters, so overall time is O(n^2).
Space Complexity
Only a few variables are used and strings are printed directly, so extra space is O(1).
Which Approach is Fastest?
For loops are fastest and simplest; recursion adds overhead and while loops are similar but less concise.
| Approach | Time | Space | Best For |
|---|---|---|---|
| For loops | O(n^2) | O(1) | Simple and clear code |
| While loops | O(n^2) | O(1) | Alternative loop style |
| Recursion | O(n^2) | O(n) | Learning recursion, less efficient |
' '.repeat() and '*'.repeat() to easily control spaces and stars in each line.