Python Program to Print Hollow Square Pattern
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 n=4 through the code to see how the hollow square is printed.
First row (i=0)
All columns j=0 to 3 print '*', so output: ****
Second row (i=1)
Columns j=0 and j=3 print '*', others print space, output: * *
Third row (i=2)
Same as second row, output: * *
Last row (i=3)
All columns print '*', output: ****
| Row i | Column j | |
|---|---|---|
| 0 | 0-3 | * |
| 1 | 0 | * |
| 1 | 1-2 | |
| 1 | 3 | * |
| 2 | 0 | * |
| 2 | 1-2 | |
| 2 | 3 | * |
| 3 | 0-3 | * |
Why This Works
Step 1: Print stars on edges
The code prints stars when the current row is the first or last, or the current column is the first or last, creating the square's border.
Step 2: Print spaces inside
For positions not on the edges, the code prints spaces to make the square hollow.
Step 3: Use nested loops
Two loops go through each row and column, deciding what to print based on position.
Alternative Approaches
n = 5 for i in range(n): if i == 0 or i == n-1: print('*' * n) else: print('*' + ' ' * (n-2) + '*')
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)))
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
The program uses only a few variables and prints directly, so space complexity is O(1).
Which Approach is Fastest?
All approaches run in O(n^2) time; string multiplication is simpler and slightly faster for edges, but nested loops offer more flexibility.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Nested loops with if | O(n^2) | O(1) | Flexible patterns |
| String multiplication | O(n^2) | O(1) | Simple hollow squares |
| List comprehension | O(n^2) | O(1) | Concise code |