712066. Pattern 12
Easy
Pattern 12
Summary
The Pattern 12 problem is about generating a double triangle pattern using asterisks (*) and spaces. The goal is to create a pattern that alternates between increasing and decreasing sequences, with each row having one more element than the previous one.
Detailed Explanation
To solve this problem, we can use a simple loop-based approach to generate the desired pattern. Here's a step-by-step breakdown of the solution:
- Initialize an empty string
resultto store the generated pattern. - Loop through the rows of the triangle (let's say up to
nrows). For each row:- Start by adding
nspaces at the beginning of the row, wherenis the current row number. - Then, add a sequence of
nasterisks (*) followed by a space. - To create the decreasing sequence, subtract 1 from
nand repeat the process until you reach the desired length.
- Start by adding
- Append each row to the
resultstring using the newline character (\n) to separate rows.
Here's an ASCII art representation of the pattern:
*
* *
* * *
* * * *
* * * * *
Time complexity: O(n), where n is the number of rows. Space complexity: O(n), since we're storing the generated pattern in a string.
Optimized Solutions
Java
public class Pattern12 {
public static void main(String[] args) {
int n = 5; // adjust this value to generate different patterns
StringBuilder result = new StringBuilder();
for (int i = 1; i <= n; i++) {
for (int j = 0; j < n - i; j++) {
result.append(" ");
}
for (int k = 0; k < 2 * i - 1; k++) {
if (k < i) {
result.append("* ");
} else {
result.append(" *");
}
}
result.append("\n");
}
System.out.println(result.toString());
}
}