Print a Diamond Star Pattern

Solve this Problem
Easy12 min
Topics
Companies
Given an integer n, return the 2n rows of a centered star diamond — a Full Star Pyramid (n rows, growing) immediately followed by a Reverse Star Pyramid (n rows, shrinking). The widest row (0 spaces, 2n − 1 stars) sits in the middle, appearing twice in a row: once as the last row of the top half, once as the first row of the bottom half. Both solutions build the two halves separately and concatenate them — reusing the exact row formulas from the Full Star Pyramid and Reverse Star Pyramid problems.

Test Case 1:

Input:n = 3
Output:[" *", " ***", "*****", "*****", " ***", " *"]
Explanation:Top half (n rows) is a Full Star Pyramid, bottom half (n rows) is a Reverse Star Pyramid.

Test Case 2:

Input:n = 1
Output:["*", "*"]
Explanation:A diamond of size 1 is still two rows — the widest row appears once at the end of each half.

Constraints

  • ◆1 ≤ n ≤ 20

Try the Dry Run

Approach & Solutions

Nested Loops — Spaces, Then StarsGood

Build the top half exactly like the Full Star Pyramid (row i: (n − i) spaces, (2i − 1) stars) with a loop from i = 1 to n, then build the bottom half exactly like the Reverse Star Pyramid (row i: (i − 1) spaces, (2(n − i + 1) − 1) stars) with a second loop from i = 1 to n, appending both halves into one 2n-row result.

TimeO(n²)
SpaceO(n²) for the output
1class Solution { 2 public String[] printDiamondPattern(int n) { 3 String[] result = new String[2 * n]; 4 int idx = 0; 5 for (int i = 1; i <= n; i++) { 6 StringBuilder row = new StringBuilder(); 7 for (int s = 1; s <= n - i; s++) { 8 row.append(' '); 9 } 10 for (int j = 1; j <= 2 * i - 1; j++) { 11 row.append('*'); 12 } 13 result[idx++] = row.toString(); 14 } 15 for (int i = 1; i <= n; i++) { 16 StringBuilder row = new StringBuilder(); 17 for (int s = 1; s <= i - 1; s++) { 18 row.append(' '); 19 } 20 for (int j = 1; j <= 2 * (n - i + 1) - 1; j++) { 21 row.append('*'); 22 } 23 result[idx++] = row.toString(); 24 } 25 return result; 26 } 27}
Built-in Repetition for Spaces and StarsOptimal

Reuse the Full Star Pyramid's one-liner for the top half and the Reverse Star Pyramid's one-liner for the bottom half, then concatenate the two. C has no repeat built-in, so it keeps both loops.

TimeO(n²)
SpaceO(n²)
1class Solution { 2 public String[] printDiamondPattern(int n) { 3 String[] result = new String[2 * n]; 4 for (int i = 1; i <= n; i++) { 5 result[i - 1] = " ".repeat(n - i) + "*".repeat(2 * i - 1); 6 } 7 for (int i = 1; i <= n; i++) { 8 result[n + i - 1] = " ".repeat(i - 1) + "*".repeat(2 * (n - i + 1) - 1); 9 } 10 return result; 11 } 12}

Related Problems