All challenges
Easy 0 solved 0% acceptance

Centered Star Pyramid

Print a centered pyramid of stars with an odd number of stars on each row.

What you'll learn

  • Work out the spaces and stars for each row
  • Center a pattern with leading spaces
  • Avoid trailing spaces in output rows

Problem

A centered pyramid has 1, 3, 5, … stars, and each row is pushed right with spaces so the peak sits in the middle. Row i (counting from 1) has n − i leading spaces followed by 2i − 1 stars. Nothing is printed after the last star.

Implement centered_star_pyramid(n).

Input

n: The number of rows (the height of the pyramid).

Output

Return the rows from top to bottom, without trailing spaces.

Constraints

0 ≤ n ≤ 100

Examples

Example 1
Input:
n = 3

Expected output:
expected = ["  *", " ***", "*****"]
Input:
long long n = 3;

Expected output:
std::vector<std::string> expected = {"  *", " ***", "*****"};
Input:
long n = 3;

Expected output:
string[] expected = new string[] {"  *", " ***", "*****"};

Explanation

Row 1 is 2 spaces and 1 star, row 2 is 1 space and 3 stars, row 3 is 5 stars: [" *", " ***", "*****"].

Example 2
Input:
n = 1

Expected output:
expected = ["*"]
Input:
long long n = 1;

Expected output:
std::vector<std::string> expected = {"*"};
Input:
long n = 1;

Expected output:
string[] expected = new string[] {"*"};

Explanation

One row with one star and no spaces: ["*"].

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

Write down rows 1 to 3 for n = 3 and count spaces and stars on each.

Hint 2

Spaces go down by one per row while stars go up by two.

Hint 3

Only add spaces before the stars, never after.

Expected complexity

O(n^2) time, O(n^2) extra space

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

The best passing solution of each coder. Faster, smaller and better-reviewed solutions rank higher.

No passing solutions yet. Solve it to take first place.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.