Print a Hollow Diamond Pattern

Solve this Problem
Easy15 min
Topics
Companies
Given n, return the 2n rows of a hollow diamond: the same outline as the Diamond pattern, but with only the border stars kept and the inside filled with spaces. Rows have no trailing spaces. The trick that keeps the code short is a single "size" number k for each row that rises 1, 2, …, n and then falls n, …, 1 — one formula covers both halves. Hollowing is then an edge checkEdge CheckTesting whether a position is the first or last in its row, and printing a star only there.: the first and last positions of a row are stars, everything between them is a space.

Test Case 1:

Input:n = 3
Output:[" *", " * *", "* *", "* *", " * *", " *"]
Explanation:The outline of the Diamond pattern: each row keeps only its first and last star, so the inside becomes spaces.

Test Case 2:

Input:n = 1
Output:["*", "*"]
Explanation:Every row is one star wide, so there is no inside to hollow out.

Constraints

  • ◆1 ≤ n ≤ 20

Try the Dry Run

Approach & Solutions

Nested Loops — Edge or GapGood

There are 2n rows. For row r, let k = r + 1 in the top half and 2n − r in the bottom half — that mirrors the shape. Row r gets (n − k) leading spaces, then 2k − 1 positions; a position holds a star only if it is the first or the last one, otherwise a space.

TimeO(n²)
SpaceO(n²) for the output
class Solution { public String[] printHollowDiamond(int n) { String[] result = new String[2 * n]; for (int r = 0; r < 2 * n; r++) { int k = r < n ? r + 1 : 2 * n - r; StringBuilder row = new StringBuilder(); for (int s = 0; s < n - k; s++) { row.append(' '); } for (int j = 1; j <= 2 * k - 1; j++) { row.append(j == 1 || j == 2 * k - 1 ? '*' : ' '); } result[r] = row.toString(); } return result; } }
Edges Plus a Gap of SpacesOptimal

Each row is either a single "*" (when k = 1) or "*", a gap of 2k − 3 spaces, and "*". Build that piece with a built-in repeat and put n − k spaces in front. C fills the row with spaces using memset and then drops the two edge stars into place.

TimeO(n²)
SpaceO(n²) for the output
class Solution { public String[] printHollowDiamond(int n) { String[] result = new String[2 * n]; for (int r = 0; r < 2 * n; r++) { int k = r < n ? r + 1 : 2 * n - r; String edges = k == 1 ? "*" : "*" + " ".repeat(2 * k - 3) + "*"; result[r] = " ".repeat(n - k) + edges; } return result; } }

Related Problems