Inverted Triangle Of Stars

Easy
0/40
Average time to solve is 20m
profile
Contributed by
17 upvotes
Asked in companies
AdobeQ2Unthinkable Solutions

Problem statement

You have been given an integer ‘N’. You need to print an inverted isosceles triangle of stars such that the height of the triangle is N.

For example :
If N = 4 then the output will
*******
 *****
  ***
   *
Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first line contains an integer 'T' which denotes the number of test cases or queries to be run. Then the test cases are as follows.

The first line of each test case contains an integer ‘N’ which denotes the height of the inverted isosceles triangle of stars to be printed.
Output Format:
For each test case, print an inverted isosceles triangle of stars such that the height of the triangle is N

Print the output of each test case in a separate line.
Constraints:
1 <= T <= 100
1 <= N <= 100

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

Can you think of running loops to make the triangle inverted and isosceles?

Approaches (1)
Brute-Force

The basic idea of this approach is to run two loops nested inside an outer loop. The inner two loops make the triangle isosceles, while the outer loop decides the height of the triangle. We can observe the number of stars required at any height ‘h’ is (2 * h - 1). 

 

  • Run two loops nested inside another loop.
  • The first inner loop adds the number of spaces before the stars of each line to make the triangle isosceles. At the ‘i’th level, the number of spaces required before the stars are ‘i’ spaces.
  • The inner second loop prints the required number of stars. At the ‘i’th level, the number of stars required after the spaces are ‘2*(h-i)+1’ stars.
  • The outer loops decide the height of the triangle.
Time Complexity

O(N ^ 2), where ‘N’ is the height of the triangle.

 

Since we are running two loops. One decides the height of the tree and the other one makes the triangle isosceles. So the overall time complexity will be O(N ^ 2)

Space Complexity

O(1)

 

Constant extra space is required.

Code Solution
(100% EXP penalty)
Inverted Triangle Of Stars
Full screen
Console