A2Z Lesson

Log in
← Back to the A2Z sheet

Step 01 Beginner Problems — Patterns

Pattern 21 — Hollow Rectangle Pattern

Medium

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?'

* * * * *
*       *
*       *
*       *
* * * * *
Output for n = 5

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).

Suggested questions

Pattern 1 — Rectangular Star Pattern The solid block this frame is carved from — compare star counts n*n vs 4n - 4.
Pattern 19 — Symmetric-Void Pattern Another figure whose identity is a border plus a managed void.
Pattern 22 — Number Pattern Cells classified by distance to the border — the natural next step from boundary tests.
Sum of Array Elements ↗ Full-grid traversal; this pattern is what happens when the traversal gains a condition.

Source note: this lesson follows the structure of Striver's public A2Z DSA course (takeUforward). Each problem links to its original platform, and all problems and content belong to their respective owners — STUDY-BUDDY does not claim ownership of the sheet or its problems, and no permission beyond public linking is claimed.