A2Z Lesson

Log in
← Back to the A2Z sheet

Step 01 Beginner Problems — Patterns

Pattern 7 — Star Pyramid

Easy

A centered pyramid of stars: a single star at the top, and each row below widens by two stars — one stepping left, one stepping right — until the base spans 2n - 1 stars. This is the first pattern that needs two inner ideas at once: leading spaces to center the row, and an odd star count 2i + 1.

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

How to think about it

Number the rows i = 0, 1, ..., n-1. Row i prints n - i - 1 blank slots followed by 2i + 1 stars. The star count is always odd — 1, 3, 5, ... — because the pyramid grows symmetrically around a fixed center column. The blank count shrinks by one per row (n - i - 1), which pulls each row's left edge one slot outward. In this spaced rendering each slot is two characters wide (a token plus its separating space), so the indent is (n - i - 1) pairs of spaces. The base row (i = n - 1) has zero blanks and 2n - 1 stars.

Code

The code computes the indent as ' ' * (n - i - 1) — two spaces per empty slot so the stars line up with the rows below — and joins 2i + 1 '*' tokens for the body, then prints indent + body. Try replacing the double-space indent with a single space and watch the pyramid lean: the alignment lives in that detail.

def pattern(n): for i in range(n): indent = " " * (n - i - 1) stars = " ".join(["*"] * (2 * i + 1)) print(indent + stars)

Key points

  • Row i: blanks = n - i - 1, stars = 2i + 1 — the two formulas move in opposite directions.
  • Pyramid widths are the odd numbers 1, 3, 5, ..., 2n - 1.
  • Each blank slot must be as wide as a printed token (2 chars here), or the centering breaks.
  • The center column never moves; every row is symmetric around it.
  • Base check: the last row has 0 leading blanks and exactly 2n - 1 stars.

Suggested questions

Pattern 8 — Inverted Star Pyramid This pyramid turned upside down — blanks grow as i instead of shrinking.
Pattern 9 — Diamond Star Pattern Pyramid stacked on its inversion makes the full diamond.
Pattern 17 — Alpha-Hill Pattern The same centered skeleton filled with a hill of letters instead of stars.
Pattern 2 — Right-Angled Triangle Pattern Strip away the centering and the star counts halve back to the basic growing triangle.

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.