Skip to main content

Pattern 10

Problem​

Geek is very fond of patterns. Once, his teacher gave him a pattern to solve. He gave Geek an integer n and asked him to build a pattern.

Help Geek to build a star pattern.

Examples:​

Example 1:

Input: 5
Output:
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*

Example 2:

Input: 3
Output:
*
* *
* * *
* *
*

Your task:​

You don't need to input anything. Complete the function printTriangle() which takes an integer n as the input parameter and prints the pattern.

  • Expected Time Complexity: O(n2)O(n^2)
  • Expected Auxiliary Space: O(1)O(1)

Constraints:​

  • 1<=n<=10001 <= n <= 1000

Solution​

Python​

def printTriangle(self, n):
for i in range(1, n+1):
print('* ' * i)
for i in range(n-1, 0, -1):
print('* ' * i)

Java​

void printTriangle(int n) {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
for (int i = n - 1; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
System.out.print("* ");
}
System.out.println();
}
}

C++​

void printTriangle(int n) {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
std::cout << "* ";
}
std::cout << std::endl;
}
for (int i = n - 1; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
std::cout << "* ";
}
std::cout << std::endl;
}
}

C​

void printTriangle(int n) {
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++) {
printf("* ");
}
printf("\n");
}
for (int i = n - 1; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
printf("* ");
}
printf("\n");
}
}
  • Time Complexity: O(n2)O(n^2)
  • Auxiliary Space: O(1)O(1)