Last Updated: 27 Nov, 2020

Repeat Triangle

Easy
Asked in companies
WalmartSimple Intelligence

Problem statement

Ninja wants to build a triangle pattern for English alphabets for a given integer input.

Example, for ‘N’ = 4

Pattern:

ABCDDCBA
 ABCCBA
  ABBA
   AA

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 one integer, ‘N’, denoting the number of alphabets.

Output Format:

For each test case, print 'N' strings denoting the pattern.

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

Note:

You do not need to input or print anything, as it has already been taken care of. Just implement the given function.

Constraints:

1 <= T <= 5
1 <= N <= 26

Time Limit = 1 sec

Approaches

01 Approach

Here we can first precompute two strings of all 26 alphabets. In our first-string ‘front’, we will store the characters from left to right, and in the second string ‘back’, we will store from right to left. Once our precomputed strings are ready, now we need to make the triangle using these strings only. For each row, we will add the calculated amount of space in a local string, and then using the substring function, we can extract the number of alphabets needed from both ‘front’ and ‘back’. Now, these local strings will be stored in an array of strings. Once we get the desired number of strings for the ‘N’ row, we can return our array of strings.

 

Algorithm:

 

  • Declare an array ‘arr’ of string type and resize it with ‘n’
  • Declare a string ‘front’ and ‘back’ where we shall precompute and store the alphabets in ascending and descending order respectively.
  • Run a loop from ‘i’ = 0 to ‘n’
    • Declare a local string for each row
    • Run a loop from ‘j’ = 0 to ‘i’
      • Add space to our local string to make the triangle-like pattern
    • Append substring of front and back to this local string
    • Push the local string to the array ‘arr’
  • Return the array ‘arr’.