Star Pattern

Easy
0/40
Average time to solve is 10m
60 upvotes
Asked in companies
PayPalInfo Edge India (Naukri.com)Blackrock

Problem statement

Pattern for N = 4

picture

The dots represent spaces.
Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line contains a single integer ‘T’ representing the number of test cases. 

The first line of each test case will contain an integer ‘N’ that is the total number of rows.
Output Format:
For each test case, print the pattern of N lines.

Output for every test case will be printed in a separate line.
Constraints :
1 <= T <= 100
1 <= N <= 100
Sample Input 1 :
2
1
2   
Sample Output 1 :
   *
   * 
  ***
Sample Input 2 :
2
3
4
Sample Output 2 :
    *
   ***
  *****
    *
   ***
  *****
 *******
Hint

Can you think of using two loops?

Approaches (1)
Brute Force

The basic idea of this approach is to print the pattern row-wise. The pattern consists of ’N’ rows. Each row contains 2 * ‘N’ - 1 star. In addition to these stars, there are leading spaces. Each row contains ‘N’ - ‘Row’ spaces (where ‘ROW’ is the current row number).


 

Here is the algorithm:


 

  1. Run a loop for ‘ROW’ = 0 to ‘N’:
    • To print spaces, create a variable ‘SPACES’ and run a loop till ’N’ - ‘ROW.’
    • To print the stars ‘*’, run another loop from 1 to 2 * ‘ROW’ - 1:
      • Inside the loop print the star.
    • Print a new line.
Time Complexity

O(N^2), where N is the number of rows.


 

Because we are using two loops, the outer loop runs for the number of rows given to us, and the inner loop prints the value for every column. Hence the time complexity is O(N^2).

Space Complexity

O(1), 

 

Because we are not using any extra space for finding our answer.

Code Solution
(100% EXP penalty)
Star Pattern
Full screen
Console