Yet another Pattern

Easy
0/40
Average time to solve is 15m
31 upvotes
Asked in companies
Tata Consultancy Services (TCS)Accenture

Problem statement

Ninja was playing with her sister to solve a puzzle pattern. However, even after taking several hours, they could not solve the problem.

A value of N is given to them, and they are asked to solve the problem. Since they are stuck for a while, they ask you to solve the problem. Can you help solve this problem?

Example : Pattern for N = 4

****
 ***     
  **
   *
Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line of input contains an integer ‘T,’ denoting the number of test cases. The test cases follow.

The first line of each test case contains a single integer ‘N’.
Output Format:
For each test case, print 'N' strings corresponding to every row in a new line (row elements not separated by space)

Print the output of each test case in a separate line.
Note (c++ ,Python):
You are not required to print the expected output; it has already been taken care of. Just implement the function.
Constraints:
1 <= T <= 50
1 <= N <= 300

Time Limit: 1 sec
Sample Input 1:
2
3
2
Sample Output 1:
***
 **     
  *

**
 *     
Explanation for Sample Input 1:
 In the first test case, the value of ‘N’ is 3, so three rows are to be printed from 1 to 3 where each row starts from 3, which goes on till 1. Hence the answer is [“***”,”**”,”*”].

 In the second test case, the value of ‘N’ is 2, so the two rows are to be printed from 1 to 3 where each row starts from 3, which goes on till 1. Hence the answer is [“**”,”*”].

Sample Input 2:

2
4
5
Sample Output 2:
****
 ***     
  **
   *

*****
 ****     
  ***
   **
    *
Hint

The idea is to use nested loops in such a way that yields the answer. 

Approaches (1)
Brute Force

The steps are as follows:

  • Since we need to start from the 0th character until the Nth character, we will try thinking forward.
  • We will iterate from i=0 to i=N. For each row in the given matrix, we will perform the following operations:
    • We will iterate through from j=0 to j=N:
      • We will print the characters: ‘*’ while traversing the inner loop only if j>=i. Otherwise print a space.
      • Also, after each iteration of the inner loop completes, print a new line.
Time Complexity

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

 

We are traversing each row of the matrix that takes O(N) time complexity, and inside each loop, we are using an additional loop twice between the columns, which takes extra time (N). Hence the overall time complexity is O(N^2).

Space Complexity

O(1), no extra space required.

 

As we are not using any extra space. Hence, the overall space complexity is O(1).

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