Sandglass Number Pattern

medium Pattern Printing

Problem

Read n and print a sandglass (hourglass) of numbers. Row i of the top half has i written n-i+1 times, separated by one space, and starts with i-1 spaces. The bottom half repeats the rows in reverse order without the narrow middle row. Total rows: 2n-1.

Constraints

  • 1 <= n <= 9

Examples

Input

3

Output

1 1 1
 2 2
  3
 2 2
1 1 1

Solutions

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

One method builds one line: row - 1 spaces and then the row number repeated n - row + 1 times. The top half goes forward and the bottom half goes backward.

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 : Sandglass of numbers.
 * Input   : One integer n (rows in the top half).
 * Output  : 2n-1 lines.
 * Approach: The top half shrinks, the bottom half grows.
 * 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 " 2 2".
    static String buildLine(int half, int row) {
        StringBuilder line = new StringBuilder(repeat(" ", row - 1));
        int count = half - row + 1;
        for (int index = 0; index < count; index++) {
            if (index > 0) {
                line.append(" ");
            }
            line.append(row);
        }
        return line.toString();
    }

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

        // Step 1: Print the top half. The rows get shorter as the row number grows.
        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 middle row is already printed.
        for (int row = half - 1; row >= 1; row--) {
            System.out.println(buildLine(half, row));
        }
    }
}
Hints (2)
  1. Build one line with a method.
  2. Top half: rows 1 to n. Bottom half: rows n-1 down to 1.