712038. Pattern 20
Pattern 20: Double Triangle Pattern
Summary
The problem involves generating a double triangle pattern, where two triangular patterns are merged to form a single pattern. The output should have a specific shape and size. This problem requires understanding of algorithms for generating patterns.
Detailed Explanation
To solve this problem, we can start by creating the first triangle with increasing numbers from 1 to n (where n is the input). Then, create the second triangle in reverse order (from n to 1) with decreasing numbers. Finally, merge these two triangles together to form a single pattern.
Here's a step-by-step breakdown of the solution:
- Initialize an empty string
resultto store the final output. - Create the first triangle by iterating from 1 to n and appending each number to
result. Each line should have one more character than the previous line, with spaces added at the beginning for alignment. - Create the second triangle in reverse order (from n to 1) and append it to
resultafter the first triangle. - Return the final output string.
Here's an ASCII art diagram of the double triangle pattern:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Time complexity: O(n^2) as we are generating two triangles with n rows each. Space complexity: O(n^2) for storing the final output string.
Optimized Solutions
Java
public class Pattern20 {
public static void main(String[] args) {
int n = 5; // input size
StringBuilder result = new StringBuilder();
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
result.append(j).append(" ");
}
result.append("\n");
}
for (int i = n; i >= 1; i--) {
for (int j = 1; j <= n - i; j++) {
result.append(i).append(" ");
}
result.append("\n");
}
System.out.println(result.toString());
}
}