Pattern 5
EasyInverted star triangle
Problem
Print an inverted star triangle for a given size n.
Use one loop for the rows and another for what goes in each row to draw the shape.
The idea
To flip a triangle, count down instead of up: row i prints n-i+1 stars. Every inverted pattern in this set comes from the same substitution.
The trick
- Row i has `n - i + 1` stars, so the first row is widest.
rows5
Step 1 of 7. Inverted triangle: row i prints (n-i+1) stars. rows 5.
1/7
Optimal
timeO(n^2)spaceO(1)
1// n = 5 produces:2// * * * * *3// * * * *4// * * *5// * *6// *7 8for i in 1..n:9 for j in 1..(n-i+1): print('* ')10 newlineInput
- grid
- 5 × 5
Memory
- rows
- 5
Output
- printed rows
- —
- rows
- 5
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.