Print a Diamond Pattern With Nested Loops

Medium ⏱ 12 min 64% acceptance ★★★★★ 4.9
Write a function diamond_pattern(n) that returns a list of strings forming a diamond of asterisks: it grows from 1 star up to 2n - 1 stars at the middle row, then shrinks back to 1 star, with each row left-padded with spaces so the diamond is horizontally centered within a field of width 2n - 1.

Examples

Example 1
Input
diamond_pattern(2)
Output
[" *", "***", " *"]
Explanation

Grows from 1 star, peaks at 3 stars (2*2-1), shrinks back to 1, each centered in width 3.

Constraints

  • n is a positive integer.
  • Total width of every row string is 2n - 1.

Topics

Loopsnested loopspattern printing

Companies

OracleDeloitte

Hints

Hint 1

Build the top half with star counts 1, 3, 5, ..., 2n-1, then mirror it (excluding the middle) for the bottom half.

Hint 2

Use `.center(width)` on the star string to handle the padding, or compute spaces manually.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.