Step 01 Beginner Problems — Patterns
Pattern 21 — Hollow Rectangle Pattern
A hollow square: stars form only the border of an n-by-n frame while the interior stays empty. It turns Pattern 1's solid block inside out — instead of asking 'how many stars per row?', you ask 'is this cell on the boundary?'
* * * * * * * * * * * * * * * *
How to think about it
Consider the n-by-n grid of cells (i, j) with rows and columns 0-based. A cell gets a star exactly when it lies on the border: i = 0 (top row), i = n - 1 (bottom row), j = 0 (left column), or j = n - 1 (right column). Interior cells (0 < i < n - 1 and 0 < j < n - 1) are blank slots. So the first and last rows are solid n-star lines, and every middle row is a star, then n - 2 blank slots, then a star. The boundary-condition test — not a count — is the idea to take away; it generalises to hollow triangles, hollow diamonds, and grids of any shape.
Code
The code special-cases the first and last rows as solid lines, and for middle rows joins a star, n - 2 blank placeholder tokens, and a star. An equivalent version loops over every cell and prints a star exactly when the border condition holds — it exposes the rule directly and extends to other shapes.
def pattern(n):
for i in range(n):
if i == 0 or i == n - 1:
print(" ".join(["*"] * n))
else:
middle = [" "] * (n - 2)
print(" ".join(["*"] + middle + ["*"]))Key points
- Star rule: print '*' exactly when i == 0 or i == n - 1 or j == 0 or j == n - 1.
- Middle rows are always: 1 star, n - 2 blanks, 1 star.
- Total stars = 4n - 4 (the perimeter) versus n*n for the solid Pattern 1.
- Placeholder blanks keep the right border aligned with the solid rows.
- Edge cases: n = 1 prints one star; n = 2 prints a solid 2x2 (no interior exists).