Print a Rhombus Star Pattern
Solve this ProblemEasy10 min
Topics
BasicsPatternsLoops
Companies
TCSInfosysWipro
Given
n, return n rows that form a rhombus (a slanted square): every row has exactly n stars, and row i is shifted right by n − i spaces.
This pattern isolates one idea: leading spacesLeading SpacesSpaces printed before the first visible character to shift a row to the right. alone can change the shape. The star count never changes from row to row — compare it with the Full Star Pyramid, where both the spaces and the stars change.
Test Case 1:
Input:n = 4
Output:[" ****", " ****", " ****", "****"]
Explanation:Every row has n stars; each row starts one space further left than the one above it.
Test Case 2:
Input:n = 1
Output:["*"]
Explanation:A single row with a single star and no shift.
Constraints
- ◆
1 ≤ n ≤ 20
Try the Dry Run
Approach & Solutions
Nested Loops — Shift, Then StarsGood
A rhombus is a square that has been slanted. Row i (1-based) is pushed right by n − i spaces and then always has n stars. One inner loop writes the spaces, a second writes the stars.
Time
O(n²)Space
O(n²) for the outputJava
class Solution {
public String[] printRhombus(int n) {
String[] result = new String[n];
for (int i = 1; i <= n; i++) {
StringBuilder row = new StringBuilder();
for (int s = 0; s < n - i; s++) {
row.append(' ');
}
for (int j = 0; j < n; j++) {
row.append('*');
}
result[i - 1] = row.toString();
}
return result;
}
}Built-in Repetition for the Shift and StarsOptimal
Replace both inner loops with built-in repeats: n − i spaces followed by n stars. In C, memset fills the spaces and the stars in two calls.
Time
O(n²)Space
O(n²) for the outputJava
class Solution {
public String[] printRhombus(int n) {
String[] result = new String[n];
for (int i = 1; i <= n; i++) {
result[i - 1] = " ".repeat(n - i) + "*".repeat(n);
}
return result;
}
}