Print a Full Star Pyramid
Solve this ProblemEasy10 min
Topics
BasicsPatternsLoops
Companies
TCSInfosysWipro
Given an integer
n, return the n rows of a centered, symmetric star pyramid — row i has (n − i) leading spaces, then (2i − 1) stars.
Unlike the Right Half Pyramid (which grows by 1 star per row and is left-aligned), this pyramid grows by 2 stars per row — one on each side — which is exactly what keeps it centered and symmetric. The nested loopsNested LoopsAn outer loop over rows, one inner loop for the leading spaces, another for the (2i-1) 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. version replaces both inner loops with two built-in calls.
Test Case 1:
Input:n = 4
Output:[" *", " ***", " *****", "*******"]
Explanation:Row i has (n − i) leading spaces, then (2i − 1) stars — a centered, symmetric pyramid.
Test Case 2:
Input:n = 1
Output:["*"]
Explanation:A single star, 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 (2i − 1) stars. The odd count 2i − 1 is what keeps the pyramid centered and symmetric — each row grows by exactly 2 stars (one on each side), unlike the Right Half Pyramid's one-star-per-row growth.
Time
O(n²)Space
O(n²) for the outputJava
1class Solution {
2 public String[] printFullStarPyramid(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 <= 2 * i - 1; 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: (n − i) spaces concatenated with (2i − 1) stars. C has no repeat built-in, so it keeps both loops.
Time
O(n²)Space
O(n²)Java
1class Solution {
2 public String[] printFullStarPyramid(int n) {
3 String[] result = new String[n];
4 for (int i = 1; i <= n; i++) {
5 result[i - 1] = " ".repeat(n - i) + "*".repeat(2 * i - 1);
6 }
7 return result;
8 }
9}