Skip to main content

Pattern 1

Problem​

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

Help Geek to build a square pattern with the help of * such that each * is space-separated in each line.

Examples:​

Example 1:

Input:
n = 3
Output:
* * *
* * *
* * *

Example 2:

Input:
n = 5
Output:
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *

Your task:​

You don't need to input anything. Complete the function printSquare() which takes an integer n as the input parameter and print 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 printSquare(self, N):
for i in range(N):
for j in range(N):
print("* ", end="")
print()

Java​

void printSquare(int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print("* ");
}
System.out.println();
}
}

C++​

void printSquare(int n) {
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
cout << "* ";
}
cout << endl;
}
}

C​

void printSquare(int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("* ");
}
printf("\n");
}
}
  • Time Complexity: O(N2)O(N^2)
  • Auxiliary Space: O(1)O(1)