Print a Hollow Square Star Pattern
Solve this ProblemEasy10 min
Topics
BasicsPatternsLoops
Companies
TCSInfosysWipro
Given
n, return an n × n square drawn with stars on its border and spaces inside.
Hollow shapes introduce conditional printingConditional PrintingDeciding, for each position, whether to print a star or a space based on a condition.: instead of printing the same character in every cell, each cell asks "am I on the edge?". The first solution asks that question cell by cell; the second notices that there are only two distinct rows and builds each just once.
Test Case 1:
Input:n = 4
Output:["****", "* *", "* *", "****"]
Explanation:The top and bottom rows are solid; middle rows have stars only in the first and last columns.
Test Case 2:
Input:n = 2
Output:["**", "**"]
Explanation:With only two rows there are no middle rows, so the square is solid.
Constraints
- ◆
1 ≤ n ≤ 20
Try the Dry Run
Approach & Solutions
Nested Loops — Border Check per CellGood
Visit every cell (i, j) of the n × n grid. A cell is on the border when it is in the first or last row, or the first or last column. Border cells get a star, the rest get a space.
Time
O(n²)Space
O(n²) for the outputJava
class Solution {
public String[] printHollowSquare(int n) {
String[] result = new String[n];
for (int i = 0; i < n; i++) {
StringBuilder row = new StringBuilder();
for (int j = 0; j < n; j++) {
boolean border = i == 0 || i == n - 1 || j == 0 || j == n - 1;
row.append(border ? '*' : ' ');
}
result[i] = row.toString();
}
return result;
}
}Two Ready-Made Row ShapesOptimal
Only two kinds of row exist: the solid edge row and the hollow middle row. Build each one once, then fill the result by picking the solid row for the first and last positions and the hollow row everywhere else. (When n is 1, the hollow row is just "*".)
Time
O(n²)Space
O(n²) for the outputJava
class Solution {
public String[] printHollowSquare(int n) {
String[] result = new String[n];
String full = "*".repeat(n);
String hollow = n == 1 ? "*" : "*" + " ".repeat(n - 2) + "*";
for (int i = 0; i < n; i++) {
result[i] = (i == 0 || i == n - 1) ? full : hollow;
}
return result;
}
}