Print a Hollow Inverted Right Triangle Star Pattern

Solve this Problem
Easy10 min
Topics
Companies
Given n, return the n rows of an upside-down hollow right triangle: the first row is n stars, and each row after it is one cell narrower, keeping stars only at its two ends. This is the Hollow Right Triangle flipped vertically, so the solid edge moves from the bottom to the top. The same edge testEdge TestChecking whether a cell lies on the outline: first cell, last cell, or the solid side of the shape. applies, but the width now shrinks (n − i + 1) instead of growing, and the special one-cell tip arrives at the end rather than the start.

Test Case 1:

Input:n = 5
Output:["*****", "* *", "* *", "**", "*"]
Explanation:The widest row is on top and solid; each following row is one narrower with stars only at its ends.

Test Case 2:

Input:n = 2
Output:["**", "*"]
Explanation:A solid row of two, then the single-star tip.

Constraints

  • ◆1 ≤ n ≤ 20

Try the Dry Run

Approach & Solutions

Nested Loops — Edge Check per CellGood

Row i (1-based) is width = n − i + 1 cells wide. A cell is an edge when it is the first or last cell of its row, or anywhere in the first row, which is the triangle's top side.

TimeO(n²)
SpaceO(n²) for the output
class Solution { public String[] printHollowReverseTriangle(int n) { String[] result = new String[n]; for (int i = 1; i <= n; i++) { int width = n - i + 1; StringBuilder row = new StringBuilder(); for (int j = 1; j <= width; j++) { boolean edge = j == 1 || j == width || i == 1; row.append(edge ? '*' : ' '); } result[i - 1] = row.toString(); } return result; } }
Solid Rows and Hollow RowsOptimal

The top row and the one-cell tip are solid; every other row is a star, width − 2 spaces and a star. Pick the shape once per row and build it with a built-in repeat (memset in C).

TimeO(n²)
SpaceO(n²) for the output
class Solution { public String[] printHollowReverseTriangle(int n) { String[] result = new String[n]; for (int i = 1; i <= n; i++) { int width = n - i + 1; if (i == 1 || width == 1) { result[i - 1] = "*".repeat(width); } else { result[i - 1] = "*" + " ".repeat(width - 2) + "*"; } } return result; } }

Related Problems