Character Diamond Pattern

medium Pattern Printing

Problem

Read n (1 to 26) and print a diamond of letters. The top half is the alphabet pyramid with n rows. The bottom half repeats the rows in reverse order without the widest row.

Constraints

  • 1 <= n <= 26

Examples

Input

3

Output

  A
 ABA
ABCBA
 ABA
  A

Solutions

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

One method builds a single line of the alphabet pyramid. We call it for the growing rows and then for the shrinking rows.

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 : Diamond of letters.
 * Input   : One integer n (rows in the top half).
 * Output  : 2n-1 lines.
 * Approach: Alphabet pyramid and its mirror.
 * 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();
}

    // This method receives the half size and a row number. It returns one line, for example "  ABA".
    static String buildLine(int half, int row) {
        StringBuilder line = new StringBuilder(repeat(" ", half - row));
        for (int index = 0; index < row; index++) {
            line.append((char) ('A' + index));
        }
        for (int index = row - 2; index >= 0; index--) {
            line.append((char) ('A' + index));
        }
        return line.toString();
    }

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

        // Step 1: Print the top half. Row numbers go from 1 up to half.
        for (int row = 1; row <= half; row++) {
            System.out.println(buildLine(half, row));
        }

        // Step 2: Print the bottom half. Start from half - 1 because the widest row is already printed.
        for (int row = half - 1; row >= 1; row--) {
            System.out.println(buildLine(half, row));
        }
    }
}
Hints (2)
  1. Reuse the alphabet pyramid line.
  2. Print the rows in reverse order for the bottom half.