Python Program to Print Hollow Square Star Pattern
for i in range(n): for j in range(n): print('*' if i==0 or i==n-1 or j==0 or j==n-1 else ' ', end='').Examples
How to Think About It
Algorithm
Code
n = 5 for i in range(n): for j in range(n): if i == 0 or i == n-1 or j == 0 or j == n-1: print('*', end='') else: print(' ', end='') print()
Dry Run
Let's trace the code for n = 3 through the loops and print decisions.
First row (i=0)
All columns j=0 to 2 print '*', so output: ***
Second row (i=1)
Columns j=0 and j=2 print '*', j=1 prints space, output: * *
Third row (i=2)
All columns j=0 to 2 print '*', output: ***
| Row (i) | Column (j) | |
|---|---|---|
| 0 | 0 | * |
| 0 | 1 | * |
| 0 | 2 | * |
| 1 | 0 | * |
| 1 | 1 | |
| 1 | 2 | * |
| 2 | 0 | * |
| 2 | 1 | * |
| 2 | 2 | * |
Why This Works
Step 1: Print border stars
The code prints stars when the current row or column is the first or last, creating the square's border with *.
Step 2: Print spaces inside
For positions inside the border, the code prints spaces to make the square hollow using print(' ').
Step 3: Use nested loops
Nested loops let us check every position in the square grid row by row and column by column.
Alternative Approaches
n = 5 for i in range(n): print(''.join('*' if i==0 or i==n-1 or j==0 or j==n-1 else ' ' for j in range(n)))
def hollow_square(n): for i in range(n): for j in range(n): if i in (0, n-1) or j in (0, n-1): print('*', end='') else: print(' ', end='') print() hollow_square(5)
Complexity: O(n^2) time, O(1) space
Time Complexity
The program uses two nested loops each running n times, so it runs in O(n^2) time.
Space Complexity
It uses constant extra space O(1) because it prints directly without storing the pattern.
Which Approach is Fastest?
Both main and alternative methods run in O(n^2) time; the difference is mainly readability and style.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Nested loops with if-else | O(n^2) | O(1) | Beginners, clarity |
| String join with conditional | O(n^2) | O(1) | Concise code, Pythonic style |
| Function encapsulation | O(n^2) | O(1) | Reusable code, modular design |