Skip to main content

Pattern 5

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 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<=1001<= n <= 100

Solution​

Python​

def printTriangle(self, N):
for i in range(1, N + 1):
for j in range(N, i - 1, -1):
print("* ", end="")
print()

Java​

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

C++​

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

C​

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