Last Updated: 26 Nov, 2020

Pattern: Triangle of numbers

Easy
Asked in companies
Info Edge India (Naukri.com)ImpelsysAthenahealth

Problem statement

Ninja is given a pattern. Now he is asked to print the same pattern for any given ‘N’ number of rows.

For example, Pattern for ‘N’ = 4 will be.
   1
  232
 34545
4567654

Input Format:

The first line contains an integer 'T' which denotes the number of test cases or queries to be run.

The first line of each test case contains a single integer ‘N’ denoting the number of rows for which pattern needs to be printed.

Output Format:

The output of each test case will be 'N' strings denoting the pattern printed for the given ‘N’ number of rows.

Output of each test case will be printed on a separate line.

Constraints:

1 <=T <= 5 
1 <= N <= 100

Where ‘T’ is the total number of test cases and ‘N’ is the given number of rows for which pattern needs to be printed.

Time limit: 1 sec

Approaches

01 Approach

We can observe that there is an ‘N’ number of rows where ‘N’ is the total number of rows to be printed. And each row exactly contains ‘N’ - ‘row’ number of spaces where ‘row’ denotes the row number starting from topmost as 1. Also, when we go left to right the value of each element in a particular row increases by one starting from the ‘row’ number and then decrements in the same column from 2* ‘row’ - 1 till 'row'.

 

 Algorithm:

 

  • Declare an array of strings say ‘result’ for storing the pattern.
  • Declare a variable ‘row’ for keeping track of the number of rows
  • Run an outer loop from ‘row’ = ‘1 to ‘row’ = ‘N’.
    • Declare an empty string for storing the values in the current row.
    • Run an inner loop for printing spaces from ‘space’ = 1 to ‘space’ = ‘N’ - ‘row’ (where ‘row’ is the current row number).
    • Initialize a variable say ‘val’ = ‘row’.
    • Run an inner loop from ‘currCol’ = 1 to ‘currCol’ = ‘row' to printing values in increasing order.
      • Append ‘val’ to the current string. and increment ‘val’ by 1.
    • Set ‘val’ = 2 * (‘row’ - 1)
    • Run an inner loop from ‘currCol’ = ‘val’ to ‘currCol’ = ‘row' to print values in decreasing order.
      • Append ‘currCol’ to the current string.
    • Add current string into ‘result’.
  • Return ‘result’.