
Introduction
The Hollow Diamond Pattern is similar to the pyramid pattern problem. The Hollow Diamond Star Program is divided into two parts: upper and lower. The upper part is almost similar to the pyramid pattern problem, and the lower part is an inverted pyramid. The main difference is that the first and last rows only have one star, while the other rows have two stars.
Example:
*
* *
* *
* *
* *
* *
* *
* *
*
Algorithm
If we clearly observe the hollow diamond pattern, we can find that the pattern can be viewed as a combination of two pyramids. The upper half is a normal star pyramid, while the lower half is an inverted pyramid.
This is a very simple pattern problem. The algorithm is as follows:
- Take the number of rows as input from the user.
- We replace the * with blank spaces in the pyramid structures.
- Only the first and last row will have one star. Others will have two stars only.
- In the upper half, the spaces are such that the first row has n (rows) spaces, the second n-1, and so on.
- We try to print two patterns: the upper triangle and the lower triangle.
If the algorithm is not very easy to understand, you should check out the code given below for the hollow diamond star pattern. Doing a dry run of the code would be even better.
Code
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of rows: ");
int n = sc.nextInt();
int i, j;
// code for the upper half
// outer loop runs for n times. n= number of rows
for (i = 1; i <= n; i++) {
// this loop prints the preceding spaces
for (j = n; j > i; j--) {
System.out.print(" ");
}
//the first star is printed after the left preceding spaces
System.out.print("*");
// this loop prints the spaces in between the two stars
// for the first and last row since there is only one star
// therefore no space is printed in between the stars
for (j = 1; j < (i - 1) * 2; j++) {
System.out.print(" ");
}
// if it is the first row change the Line
// else print the second star also
if (i == 1) {
System.out.println();
} else {
System.out.println("*");
}
}
// code for the lower half
// outer loop runs for n-1 times
for (i = n - 1; i >= 1; i--) {
// this loop prints the spaces
for (j = n; j > i; j--) {
System.out.print(" ");
}
// print the star after all the left spaces are done
System.out.print("*");
// print the spaces between the stars
// for the last row there is only one star so no space is printed
for (j = 1; j < (i - 1) * 2; j++) {
System.out.print(" ");
}
// if we reached the last row change the line. We are done.
// else print the second star also
if (i == 1) {
System.out.println();
} else {
System.out.println("*");
}
}
}
}
Input:
n=8
Output:
*
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
*
Time and Space Complexity
The Time Complexity of the above code is O(n2).
The Space Complexity of the above code is O(1) as no extra space is used.