Hourglass Star Pattern

medium Pattern Printing

Problem

Read n and print an hourglass of stars. The top half is an upside-down pyramid with n rows. The bottom half is a normal pyramid that starts from its second row. The hourglass has 2n-1 rows.

Constraints

  • 1 <= n <= 50

Examples

Input

3

Output

*****
 ***
  *
 ***
*****

Solutions

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

The hourglass is the diamond with the two halves swapped. The same line-building method is used, only the row order is different.

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 : Hourglass of stars.
 * Input   : One integer n (rows in the top half).
 * Output  : 2n-1 lines.
 * Approach: Print an inverted pyramid and then a pyramid.
 * 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 of the pyramid.
    static String buildLine(int half, int row) {
        return repeat(" ", half - row) + repeat("*", 2 * row - 1);
    }

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

        // Step 1: Print the top half. Start with the widest row and go down to the narrow row.
        for (int row = half; row >= 1; row--) {
            System.out.println(buildLine(half, row));
        }

        // Step 2: Print the bottom half. Start from row 2 because the narrow row is already printed.
        for (int row = 2; row <= half; row++) {
            System.out.println(buildLine(half, row));
        }
    }
}
Hints (2)
  1. Compare it with the diamond pattern.
  2. Which half do you print first?