Diamond of Stars

Easy
0/40
Average time to solve is 10m
profile
Contributed by
44 upvotes
Asked in companies
DeloitteCompro TechnologiesAppSuccessor

Problem statement

You are given an integer ‘N’. Your task is to print the following pattern for the ‘N’ number of rows.

For Example:
Pattern for ‘N’ = 5:

The dots represent spaces. Note:
‘N’ is always odd.
Detailed explanation ( Input/output format, Notes, Images )
Input format :
The first line of input contains ‘T’, denoting the number of test cases. Then each test case follows.

Each test case contains a single integer ‘N’, denoting the number given.
Output format :
For each test case print 'N' strings denoting the pattern. 
Constraints :
1 <= ‘T’ <= 5
1 <= ‘N’ <= 600

Time limit = 1 sec.
Sample Input 1:
2
5
1
Sample Output 1:
  *
 ***
*****
 ***
  *
*

Explanation of the Sample Input 1:

For test case 1: 
The pattern for ‘N’ = 5, will be as given above.

For test case 2: 
The pattern for ‘N’ = 1, will be as given above.
Sample Input 2:
3
7
Sample Output 2:
 *
***
 *
   *
  ***
 *****
*******
 *****
  ***
   *
Hint

Try to divide problems into the upper half and lower half.

Approaches (1)
Observation

The main idea is to divide the pattern into two halves, the upper half and the lower half, and print them separately.

 

The steps are as follows:

  • Declare a variable ‘currRow’ and initialize it to 1.
  • Execute a while loop with the condition that ‘currRow’ is less than equal to ‘N’/2 + 1:
    • Maintain a variable ‘spaces’ which tells us how many spaces to give.
    • Print ‘N’/2 + 1 - ‘currRow’ spaces.
    • Declare a variable ‘currCol’ = 1.
    • Loop while ‘currCol’ is less than equal to (2 * ‘currRow’) - 1
      • Print stars ‘*’
      • Increase ‘currCol’ by 1.
    • End with a line.
  • Repeat the same task for the bottom half, but this time ‘currRow’ would go till ‘N’/2 and ‘currCol’ will start from 2 * ((‘N’ / 2) 0 ‘currRow’ + 1) - 1 and go till 1.
Time Complexity

O(N ^ 2), where ‘N’ is the number given.


Since we are doing N ^ 2 computation at max. Therefore, the overall time complexity will be O(N ^ 2).

Space Complexity

O(1).


 Since we are not using any extra space. Therefore, the overall space complexity will be O(1).

Code Solution
(100% EXP penalty)
Diamond of Stars
Full screen
Console