AlgoViz

Pattern 18

Easy

Triangle of trailing letters

Problem

Print an alphabet triangle of trailing letters 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

Each row ends at the same final letter and starts further back as the rows grow, so the starting letter is what changes. Work out the first letter of the row and then count forwards.

The trick

  • Row i starts at 'A' + (n - i) and runs to 'A' + (n - 1).
rows5

Step 1 of 7. Trailing letters: row i prints the last i letters up to E. rows 5.

1/7
Optimal
timeO(n^2)spaceO(1)
1// n = 5 produces:2// E3// D E4// C D E5// B C D E6// A B C D E7 8for i in 1..n:9  for j in (n-i)..(n-1): print(char('A'+j))10  newline

Input

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:
E / D E / C D E / B C D E / A B C D E

Finished the walkthrough? Add it to your streak.