JavaScript Program to Print Inverted Pyramid Pattern
for (let i = n; i >= 1; i--) { console.log(' '.repeat(n - i) + '* '.repeat(i)); } where n is the number of rows.Examples
How to Think About It
Algorithm
Code
function printInvertedPyramid(n) { for (let i = n; i >= 1; i--) { const spaces = ' '.repeat(n - i); const stars = '* '.repeat(i); console.log(spaces + stars); } } printInvertedPyramid(5);
Dry Run
Let's trace printing an inverted pyramid with 3 rows through the code.
Start outer loop with i = 3
spaces = ' '.repeat(0) = '', stars = '* '.repeat(3) = '* * * ', print '* * * '
Next iteration i = 2
spaces = ' '.repeat(1) = ' ', stars = '* '.repeat(2) = '* * ', print ' * * '
Next iteration i = 1
spaces = ' '.repeat(2) = ' ', stars = '* '.repeat(1) = '* ', print ' * '
| i | spaces | stars | printed line |
|---|---|---|---|
| 3 | '' | '* * * ' | * * * |
| 2 | ' ' | '* * ' | * * |
| 1 | ' ' | '* ' | * |
Why This Works
Step 1: Outer loop controls rows
The loop runs from the total number of rows down to 1, reducing stars each time to create the inverted shape.
Step 2: Spaces align the pyramid
Spaces before stars increase each row to push the stars right, maintaining the pyramid shape.
Step 3: Stars print the pattern
Stars are repeated according to the current row number, decreasing each row to form the inverted pyramid.
Alternative Approaches
function printInvertedPyramidNested(n) { for (let i = n; i >= 1; i--) { let line = ''; for (let s = 0; s < n - i; s++) { line += ' '; } for (let star = 0; star < i; star++) { line += '* '; } console.log(line); } } printInvertedPyramidNested(5);
function printInvertedPyramidRec(n, current = n) { if (current === 0) return; console.log(' '.repeat(n - current) + '* '.repeat(current)); printInvertedPyramidRec(n, current - 1); } printInvertedPyramidRec(5);
Complexity: O(n^2) time, O(n) space
Time Complexity
The outer loop runs n times and the inner string repeat operations take up to n steps, resulting in O(n^2) time.
Space Complexity
Extra space is used for strings of spaces and stars each line, up to O(n), but no large additional data structures.
Which Approach is Fastest?
Using string repeat is generally faster and cleaner than nested loops or recursion for this pattern.
| Approach | Time | Space | Best For |
|---|---|---|---|
| String repeat | O(n^2) | O(n) | Clean and efficient for pattern printing |
| Nested loops | O(n^2) | O(n) | Clear logic, easier for beginners |
| Recursion | O(n^2) | O(n) | Alternative style, less common for simple patterns |
' '.repeat() and '* '.repeat() to easily create spaces and stars for each line.