Print a Hollow Hourglass Star Pattern

Solve this Problem
Easy15 min
Topics
Companies
Given n, return the 2n − 1 rows of a hollow hourglass: a solid top row of 2n − 1 stars, rows that narrow to a single-star waist, then rows that widen back out to a solid bottom row. Between the lids only the outline is drawn. The hourglass is a reverse pyramid stacked on a pyramid, sharing the middle row. A single number k = |n − 1 − r| + 1, built with the absolute valueAbsolute ValueThe distance of a number from zero, ignoring its sign: |−2| = |2| = 2., rises and falls in a V shape and drives both halves at once, so there is no need for two separate loops.

Test Case 1:

Input:n = 3
Output:["*****", " * *", " *", " * *", "*****"]
Explanation:Solid top and bottom rows, a single-star waist in the middle, and only the outline in between.

Test Case 2:

Input:n = 1
Output:["*"]
Explanation:The top, waist and bottom are all the same single row.

Constraints

  • ◆1 ≤ n ≤ 20

Try the Dry Run

Approach & Solutions

Nested Loops — Edge Check per CellGood

There are 2n − 1 rows. For row r let k = |n − 1 − r| + 1: it falls from n to 1 at the middle row and climbs back to n. Each row has n − k leading spaces and 2k − 1 cells; a cell is a star if it is the first or last of the row, or if the row is the top or bottom (k = n).

TimeO(n²)
SpaceO(n²) for the output
class Solution { public String[] printHollowHourglass(int n) { String[] result = new String[2 * n - 1]; for (int r = 0; r < 2 * n - 1; r++) { int k = Math.abs(n - 1 - r) + 1; StringBuilder row = new StringBuilder(); for (int s = 0; s < n - k; s++) { row.append(' '); } for (int j = 1; j <= 2 * k - 1; j++) { boolean edge = j == 1 || j == 2 * k - 1 || k == n; row.append(edge ? '*' : ' '); } result[r] = row.toString(); } return result; } }
Pick the Row Body by Its WidthOptimal

Classify each row by k: k = n gives a solid body of 2n − 1 stars, k = 1 gives a single star, anything else is "*", 2k − 3 spaces and "*". Prefix n − k spaces. C fills the row with spaces (or stars for the solid rows) using memset and then sets the two edge characters.

TimeO(n²)
SpaceO(n²) for the output
class Solution { public String[] printHollowHourglass(int n) { String[] result = new String[2 * n - 1]; for (int r = 0; r < 2 * n - 1; r++) { int k = Math.abs(n - 1 - r) + 1; String body; if (k == n) { body = "*".repeat(2 * n - 1); } else if (k == 1) { body = "*"; } else { body = "*" + " ".repeat(2 * k - 3) + "*"; } result[r] = " ".repeat(n - k) + body; } return result; } }

Related Problems