Print a Right Pascal's Triangle Star Pattern

Solve this Problem
Easy10 min
Topics
Companies
Given n, return 2n − 1 left-aligned rows of stars whose lengths go 1, 2, …, n and then back down to 1 — an arrow pointing to the right. (The name comes from its outline, not from Pascal's number triangle.) It is a Right Half Pyramid followed by its reverse, sharing the widest row. The first solution writes the two halves with two loops; the second uses the distance from the middleDistance from the MiddleFor row r, |n − 1 − r| counts how many rows it is away from the widest row; the width shrinks by one per step. to give every row its width in a single loop.

Test Case 1:

Input:n = 3
Output:["*", "**", "***", "**", "*"]
Explanation:Rows grow from 1 star to n stars and then shrink back to 1, forming an arrow pointing right.

Test Case 2:

Input:n = 1
Output:["*"]
Explanation:Only the single widest row.

Constraints

  • ◆1 ≤ n ≤ 20

Try the Dry Run

Approach & Solutions

Rising Loop, Then Falling LoopGood

Two plain loops: the first writes rows of 1, 2, …, n stars, the second writes rows of n − 1, …, 1 stars. The widest row is written only by the first loop, so it is not repeated. C uses a small helper that returns a row of a given number of stars.

TimeO(n²)
SpaceO(n²) for the output
class Solution { public String[] printRightPascalsTriangle(int n) { String[] result = new String[2 * n - 1]; int idx = 0; for (int i = 1; i <= n; i++) { result[idx++] = "*".repeat(i); } for (int i = n - 1; i >= 1; i--) { result[idx++] = "*".repeat(i); } return result; } }
One Loop, Width from the Distance to the MiddleOptimal

Use a single loop over all 2n − 1 rows. Row r is |n − 1 − r| rows away from the middle row, and each step away from the middle removes one star, so its width is n − |n − 1 − r|. One formula covers both the rising and the falling half.

TimeO(n²)
SpaceO(n²) for the output
class Solution { public String[] printRightPascalsTriangle(int n) { String[] result = new String[2 * n - 1]; for (int r = 0; r < 2 * n - 1; r++) { int width = n - Math.abs(n - 1 - r); result[r] = "*".repeat(width); } return result; } }

Related Problems