Print a Left Half Pyramid Star Pattern
Solve this ProblemEasy10 min
Topics
BasicsPatternsLoops
Companies
TCSInfosysWipro
Given an integer
n, return the n rows of a right-aligned star pyramid — row i has (n − i) leading spaces followed by i stars.
This mirrors the Right Half Pyramid, but with the stars pushed to the right edge of each row instead of the left — which is exactly what makes the slanted edge appear on the LEFT side of the shape. The nested loopsNested LoopsAn outer loop over rows, with one inner loop for the leading spaces and another for the stars. version builds each half explicitly; the built-in repetitionBuilt-in RepetitionBuilding the space-padding and the stars each with a repeat call, then concatenating the two pieces — no inner loop at all. version replaces both inner loops with two repeat calls and a concatenation.
Test Case 1:
Input:n = 4
Output:[" *", " **", " ***", "****"]
Explanation:Row i has (n − i) leading spaces then i stars — right-aligned, so the slanted edge is on the left.
Test Case 2:
Input:n = 1
Output:["*"]
Explanation:A single row, no spaces needed.
Constraints
- ◆
1 ≤ n ≤ 20
Try the Dry Run
Approach & Solutions
Nested Loops — Spaces, Then StarsGood
For row i, first append (n − i) spaces, then append i stars. The stars end up right-aligned, which is what makes the slanted edge appear on the LEFT side of the pyramid instead of the right.
Time
O(n²)Space
O(n²) for the outputJava
1class Solution {
2 public String[] printLeftHalfPyramid(int n) {
3 String[] result = new String[n];
4 for (int i = 1; i <= n; i++) {
5 StringBuilder row = new StringBuilder();
6 for (int s = 1; s <= n - i; s++) {
7 row.append(' ');
8 }
9 for (int j = 1; j <= i; j++) {
10 row.append('*');
11 }
12 result[i - 1] = row.toString();
13 }
14 return result;
15 }
16}Built-in Repetition for Spaces and StarsOptimal
Build each half of the row with a built-in repeat instead of a loop: (n − i) spaces, concatenated with i stars. Two repeats and one concatenation, no inner loop. C has no repeat built-in, so it keeps both loops.
Time
O(n²)Space
O(n²)Java
1class Solution {
2 public String[] printLeftHalfPyramid(int n) {
3 String[] result = new String[n];
4 for (int i = 1; i <= n; i++) {
5 result[i - 1] = " ".repeat(n - i) + "*".repeat(i);
6 }
7 return result;
8 }
9}