Star Triangle

Easy
0/40
profile
Contributed by
353 upvotes
Asked in company
Appinventiv

Problem statement

Ninja was very fond of patterns. For a given integer ‘N’, he wants to make the N-Star Triangle.

Example:
Input: ‘N’ = 3

Output: 

  *
 ***
*****
Detailed explanation ( Input/output format, Notes, Images )
Input Format:
The first and only line of each test case contains an integer ‘N’.
Output format:
Return a 2D array of characters that represents the N-Star Pattern.
Constraints :
1  <= N <= 20
Time Limit: 1 sec
Sample Input 1:
3
Sample Output 1:
  *
 ***
*****
Explanation Of Sample Input 1 :
The first row contains two spaces, followed by a star.
The second row contains one space, followed by three stars.
The third row contains five stars.
Sample Input 2 :
1
Sample Output 2 :
*
Hint

Iterate to all the cells .

Approaches (1)
Brute Force

Approach: 

The solution is iterating on the pattern and printing every cell with ‘*’ or spaces.

The steps are as follows :

Function void nStarTriangle(int ‘N’)

 

  1. Int ‘gap’ = ‘N’-1, ‘stars’ = 1.
  2. For ‘i’ from 0 to ‘N’-1:
    • For j from 0 to ‘gap’-1:
      • Print ’ ’
    • For j from gap+1 to gap+stars-1:
      • Print ’*’
    • gap–
    • star+=2
Time Complexity

O( N * N ), Where N is the given input integer. 

Two nested loops are running N*(2*N-1) times so that time complexity would be the order of NxN.

Hence the time complexity is O( N * N ). 

Space Complexity

O(1)

Since we are using constant extra space.

 

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