Print a Right Half Pyramid Star Pattern
Solve this ProblemEasy5–10 min
Topics
BasicsPatternsLoops
Companies
TCSInfosysWipro
Given an integer
n, return the n rows of a left-aligned star pyramid — row i has i stars, growing one star per row.
The nested loopsNested LoopsAn outer loop over rows, an inner loop that appends exactly i stars for row i. version builds every row's stars one at a time. The string repetitionString Repetition per RowUsing a built-in repeat to build each differently-sized row directly, removing just the inner loop (the outer loop over rows still varies the length). version removes the inner loop specifically, since each row's content is just "repeat '*' i times" — still the same total O(n²) work (1+2+...+n stars), just expressed without the character-by-character detail.
Test Case 1:
Input:n = 4
Output:["*", "**", "***", "****"]
Explanation:Row i has i stars, left-aligned — growing one star per row.
Test Case 2:
Input:n = 1
Output:["*"]
Explanation:A single row, a single star.
Constraints
- ◆
1 ≤ n ≤ 20
Try the Dry Run
Approach & Solutions
Nested Loops — Print Each CharacterGood
For row i (from 1 to n), run an inner loop that appends i stars — one more than the row before it. Left-aligned, so no spaces are ever needed.
Time
O(n²)Space
O(n²) for the outputJava
1class Solution {
2 public String[] printRightHalfPyramid(int n) {
3 String[] result = new String[n];
4 for (int i = 1; i <= n; i++) {
5 StringBuilder row = new StringBuilder();
6 for (int j = 1; j <= i; j++) {
7 row.append('*');
8 }
9 result[i - 1] = row.toString();
10 }
11 return result;
12 }
13}String Repetition per RowOptimal
Row i is just i stars — build it directly with a built-in repeat instead of an inner loop. The outer loop over rows is still needed (each row has a different length), but the character-by-character inner loop disappears. C has no repeat built-in, so it keeps both loops.
Time
O(n²)Space
O(n²)Java
1class Solution {
2 public String[] printRightHalfPyramid(int n) {
3 String[] result = new String[n];
4 for (int i = 1; i <= n; i++) {
5 result[i - 1] = "*".repeat(i);
6 }
7 return result;
8 }
9}