711625. Pattern 2
Easy
Pattern 2: Right Triangle
Summary
This problem involves generating a right triangle pattern with asterisks (*) and spaces. The pattern starts with one asterisk, then two asterisks separated by a space, three asterisks separated by two spaces, and so on.
Detailed Explanation
To solve this problem, we can use a simple loop that prints the required number of asterisks and spaces for each row. Here's the step-by-step breakdown:
- Initialize an integer
nto represent the number of rows in the triangle. - Loop through each row from 1 to
n. - For each row, print the required number of spaces (equal to the current row number minus 1).
- Print the required number of asterisks (equal to the current row number).
- Print a newline character to move to the next line.
Here's an ASCII art diagram to illustrate the pattern:
*
* *
* * *
* * * *
...
The time complexity for this solution is O(n), where n is the number of rows in the triangle. The space complexity is O(1), since we only use a constant amount of space to store the variables.
Optimized Solutions
Java
public class RightTriangle {
public static void main(String[] args) {
int n = 5; // adjust this value for the desired number of rows
for (int i = 1; i <= n; i++) {
for (int j = 0; j < i - 1; j++) {
System.out.print(" ");
}
for (int k = 0; k < i; k++) {
System.out.print("*");
}
System.out.println();
}
}
}