Print a Reverse Star Pyramid
Solve this ProblemEasy10 min
Topics
BasicsPatternsLoops
Companies
TCSInfosysWipro
Given an integer
n, return the n rows of an upside-down centered star pyramid — row i has (i − 1) leading spaces, then (2(n − i + 1) − 1) stars.
This is the Full Star Pyramid, flipped: the widest row (2n − 1 stars, no spaces) comes first, shrinking by 2 stars — and gaining one leading space — each row after. Both solutions carry over the Full Star Pyramid's technique directly, just with (i − 1) and (2(n − i + 1) − 1) swapped in for the space and star counts.
Test Case 1:
Input:n = 4
Output:["*******", " *****", " ***", " *"]
Explanation:Row i has (i − 1) leading spaces, then (2(n − i + 1) − 1) stars.
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 (i − 1) spaces, then append (2(n − i + 1) − 1) stars. The upside-down version of the Full Star Pyramid: the widest row (all 2n − 1 stars, no spaces) comes first, shrinking by 2 stars — and gaining one leading space — each row after.
Time
O(n²)Space
O(n²) for the outputJava
1class Solution {
2 public String[] printReverseStarPyramid(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 <= i - 1; s++) {
7 row.append(' ');
8 }
9 for (int j = 1; j <= 2 * (n - i + 1) - 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: (i − 1) spaces concatenated with (2(n − i + 1) − 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[] printReverseStarPyramid(int n) {
3 String[] result = new String[n];
4 for (int i = 1; i <= n; i++) {
5 result[i - 1] = " ".repeat(i - 1) + "*".repeat(2 * (n - i + 1) - 1);
6 }
7 return result;
8 }
9}