Python Program to Print Hollow Pyramid Pattern
for i in range(1, n+1): print(' '*(n-i) + '*' + ' '*(2*i-3) + ('*' if i>1 else '')).Examples
How to Think About It
Algorithm
Code
n = int(input("Enter the number of rows: ")) for i in range(1, n + 1): print(' ' * (n - i), end='') if i == 1: print('*') elif i == n: print('*' * (2 * n - 1)) else: print('*' + ' ' * (2 * i - 3) + '*')
Dry Run
Let's trace the program for input n=3 to see how it prints the hollow pyramid.
Row 1
Print 2 spaces, then a single star: ' *'
Row 2
Print 1 space, star, 1 space, star: ' * *'
Row 3
Print 0 spaces, then 5 stars: '*****'
| Row | Spaces before stars | Stars and spaces printed |
|---|---|---|
| 1 | 2 | * |
| 2 | 1 | * * |
| 3 | 0 | ***** |
Why This Works
Step 1: Centering the pyramid
We print n - i spaces before stars to center the pyramid on each row.
Step 2: Printing stars on edges
For rows except the first and last, we print a star at the start and end of the row to create the hollow effect.
Step 3: Filling the base
On the last row, we print all stars without spaces to form the solid base of the pyramid.
Alternative Approaches
n = int(input('Enter rows: ')) for i in range(1, n+1): line = [' '] * (n - i) + ['*'] if i == 1: print(''.join(line)) elif i == n: print('*' * (2*n - 1)) else: line += [' '] * (2*i - 3) + ['*'] print(''.join(line))
def print_row(i, n): if i > n: return print(' ' * (n - i), end='') if i == 1: print('*') elif i == n: print('*' * (2*n - 1)) else: print('*' + ' ' * (2*i - 3) + '*') print_row(i+1, n) n = int(input('Enter rows: ')) print_row(1, n)
Complexity: O(n^2) time, O(1) space
Time Complexity
The program uses nested loops implicitly by printing spaces and stars for each row, leading to O(n^2) time as the number of characters printed grows with the square of n.
Space Complexity
The program uses constant extra space, only storing counters and temporary strings, so space complexity is O(1).
Which Approach is Fastest?
All approaches have similar time complexity; the iterative loop method is simplest and most efficient in practice.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Iterative loops | O(n^2) | O(1) | Simplicity and efficiency |
| String join with list | O(n^2) | O(n) | Easier line construction, more memory |
| Recursion | O(n^2) | O(n) | Elegant code, less efficient for large n |