Pattern 15
EasyShrinking alphabet triangle
Problem
Print a shrinking alphabet 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
The inverted triangle with letters: row i prints A through the (n-i+1)-th letter. Shape from the inverted formula, content from character arithmetic.
The trick
- Row i prints n - i + 1 letters, starting at A each time.
rows5
Step 1 of 7. Shrinking alphabet triangle. rows 5.
1/7
Optimal
timeO(n^2)spaceO(1)
1// n = 5 produces:2// A B C D E3// A B C D4// A B C5// A B6// A7 8for i in 1..n:9 for j in 0..(n-i): print(char('A'+j))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:
- A B C D E / A B C D / A B C / A B / A
Finished the walkthrough? Add it to your streak.