AlgoViz

Pattern 10

Easy

Star hill that grows then shrinks

Problem

Print a star hill that grows to n then shrinks for a given size n.

In simple words

Use one loop for the rows and another for what goes in each row to draw the shape.

The idea

Run one loop over 2n-1 rows and let the star count grow to n and then fall back. Deriving the count from the row index — rather than writing two loops — is the trick worth practising here.

The trick

  • For row i in 1..2n-1, stars = i <= n ? i : 2n - i.
rows9

Step 1 of 11. Hill: star count climbs 1..n then falls back to 1. rows 9.

1/11
Optimal
timeO(n^2)spaceO(1)
1// n = 5 produces:2// *3// **4// ***5// ****6// *****7// ****8// ***9// **10// *11 12for i in 1..2n-1:13  k = i <= n ? i : 2n - i14  print '*' x k

Input

grid
9 × 5

Memory

rows
9

Output

printed rows
rows
9

Check yourself

3 quick questions about this walkthrough. A wrong answer costs nothing.

Example

Input:
n = 5
Output:
★ / ★ ★ / ★ ★ ★ / ★ ★ ★ ★ / ★ ★ ★ ★ ★ / ★ ★ ★ ★ / ★ ★ ★ / ★ ★ / ★

Finished the walkthrough? Add it to your streak.