Reverse Alphabet Triangle
Problem
Read n (1 to 26) and print a triangle where every row starts with the n-th letter and goes backward. Row i has i letters. Example for n = 4: D, DC, DCB, DCBA.
Constraints
- 1 <= n <= 26
Examples
Input
3
Output
C CB CBA
Solutions
The first letter of every row is the n-th letter. Each next letter is one step lower in the alphabet.
Java 8 has no String.repeat, so we use a small helper method. In Java 11 and newer you can write " ".repeat(count).
/*
* Problem : Triangle of letters going backward.
* Input : One integer n (rows).
* Output : n lines of letters.
* Approach: Start from the n-th letter and count down.
* Time : O(n^2)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int rows = new Scanner(System.in).nextInt();
// Step 1: Find the last letter that we need. Example: n = 4 -> D.
char lastLetter = (char) ('A' + rows - 1);
// Step 2: Repeat once for each row. Row numbers go from 1 to rows.
for (int row = 1; row <= rows; row++) {
StringBuilder line = new StringBuilder();
// Step 3: Write "row" letters. Start from the last letter and go backward.
for (int step = 0; step < row; step++) {
line.append((char) (lastLetter - step));
}
// Step 4: Print the finished line.
System.out.println(line);
}
}
}
Hints (2)
- Use an outer loop for rows and an inner loop for the letters or digits.
- Write the output for n = 3 and look for the rule.