Alphabet Pyramid Pattern

medium Pattern Printing

Problem

Read n (1 to 26) and print a centered pyramid. Row i goes up from A to the i-th letter and then comes down again without repeating the top letter. Example row 3: ABCBA.

Constraints

  • 1 <= n <= 26

Examples

Input

3

Output

  A
 ABA
ABCBA

Solutions

Best approachTime O(n^2)Space O(1)

Each row is spaces + letters going up + letters going down. The down loop starts one letter below the top, so the top letter is not repeated. In Java, a char is a number inside the computer. 'A' + 1 is the number of 'B', so we cast the result back to char.

Same code works in Java810172125Basic features only, so nothing changes between versions.

Java 8 has no String.repeat, so we use a small helper method. In Java 11 and newer you can write " ".repeat(count).

/*
 * Problem : Centered alphabet pyramid.
 * Input   : One integer n (rows).
 * Output  : n lines.
 * Approach: Spaces, letters going up, letters going down.
 * Time    : O(n^2)
 * Space   : O(1)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method returns the text repeated "count" times. Java 11 has String.repeat for this.
static String repeat(String text, int count) {
    StringBuilder result = new StringBuilder();
    for (int i = 0; i < count; i++) {
        result.append(text);
    }
    return result.toString();
}

    public static void main(String[] args) {
        int rows = new Scanner(System.in).nextInt();

        // Step 1: Repeat once for each row. Row numbers go from 1 to rows.
        for (int row = 1; row <= rows; row++) {
            // Step 2: Print the spaces first. Row 1 needs the most spaces.
            StringBuilder line = new StringBuilder(repeat(" ", rows - row));

            // Step 3: Go up from A to the letter of this row. Example: row 3 -> ABC.
            for (int index = 0; index < row; index++) {
                line.append((char) ('A' + index));
            }

            // Step 4: Go down again, but skip the top letter. Example: row 3 -> BA.
            for (int index = row - 2; index >= 0; index--) {
                line.append((char) ('A' + index));
            }

            // Step 5: Print the finished line. Example: ABCBA.
            System.out.println(line);
        }
    }
}
Hints (2)
  1. Combine the pyramid pattern with the alphabet triangle.
  2. The down part starts one letter lower than the top letter.