Palindromic Number Pyramid

medium Pattern Printing

Problem

Read n (at most 9) and print a centered pyramid. Row i counts up from 1 to i and then down to 1 without spaces between digits. Example row 3: 12321.

Constraints

  • 1 <= n <= 9 (so each number is one digit)

Examples

Input

3

Output

  1
 121
12321

Solutions

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

Each row has two loops: one counts up to the row number and one counts down from row - 1. The row reads the same from both sides, so it is a palindrome.

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 : Palindromic number pyramid.
 * Input   : One integer n (1 to 9).
 * Output  : n lines.
 * Approach: Count up to the row number, then count 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: Count up from 1 to the row number. Example: row 3 -> 123.
            for (int number = 1; number <= row; number++) {
                line.append(number);
            }

            // Step 4: Count down from row - 1 to 1. Example: row 3 -> 21.
            for (int number = row - 1; number >= 1; number--) {
                line.append(number);
            }

            // Step 5: Print the finished line. Example: 12321.
            System.out.println(line);
        }
    }
}
Hints (2)
  1. Use one loop up and one loop down.
  2. Why does the down loop start at row - 1?