Print a Hollow Right Triangle Star Pattern
Solve this ProblemEasy10 min
Topics
BasicsPatternsLoops
Companies
TCSInfosysWipro
Given
n, return the n rows of a hollow right-angled triangle: row i is i characters wide, with stars along the left side, the slanted side and the base, and spaces inside.
It is the Right Half Pyramid with its inside removed. The new idea is that the edge conditionEdge ConditionA boolean test such as j == 1 || j == i || i == n that is true exactly on the outline of the shape. combines column checks (first and last cell) with a row check (the base). No trailing spaces are produced, because every row ends with a star.
Test Case 1:
Input:n = 5
Output:["*", "**", "* *", "* *", "*****"]
Explanation:Row i has i positions; only its first and last are stars, except the bottom row, which is solid.
Test Case 2:
Input:n = 2
Output:["*", "**"]
Explanation:Both rows are edges, so nothing is hollow yet.
Constraints
- ◆
1 ≤ n ≤ 20
Try the Dry Run
Approach & Solutions
Nested Loops — Edge Check per CellGood
Row i has i cells. A cell is an edge if it is the first one (left side), the last one (the slanted side), or anywhere in the last row (the base). Edges get a star; everything else a space.
Time
O(n²)Space
O(n²) for the outputJava
class Solution {
public String[] printHollowTriangle(int n) {
String[] result = new String[n];
for (int i = 1; i <= n; i++) {
StringBuilder row = new StringBuilder();
for (int j = 1; j <= i; j++) {
boolean edge = j == 1 || j == i || i == n;
row.append(edge ? '*' : ' ');
}
result[i - 1] = row.toString();
}
return result;
}
}Solid Rows and Hollow RowsOptimal
Decide per row instead of per cell. The first row (the tip) and the last row (the base) are solid: i stars. Every other row is a star, i − 2 spaces and a star. C fills a hollow row with spaces and then sets its two end characters.
Time
O(n²)Space
O(n²) for the outputJava
class Solution {
public String[] printHollowTriangle(int n) {
String[] result = new String[n];
for (int i = 1; i <= n; i++) {
if (i == 1 || i == n) {
result[i - 1] = "*".repeat(i);
} else {
result[i - 1] = "*" + " ".repeat(i - 2) + "*";
}
}
return result;
}
}