VOOZH about

URL: https://www.geeksforgeeks.org/dsa/y-shaped-pattern/

⇱ Y shaped pattern - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Y shaped pattern

Last Updated : 26 Sep, 2022

Print a ‘Y’ shaped pattern from asterisks in N number of lines.

Examples:

Input: N = 12
Output:

*             *
 *           *
  *         *
   *       *
    *     *
     *   *
      * *
       *
       *
       *
       *
       *
 

Input: 8
Output

*         *
 *       *
  *     *
   *   *
    * *
     *
     *
     *

Approach:

Follow the steps to solve this problem:

  • Initialize two variable s = N / 2 and t = N / 2.
  • Traverse a loop on i from 0 till N-1
  • Check if i > s
    • Traverse a loop on j from 0 till s-1 and print " " i.e., space
  • Else,  
    • Iterate on j from 0 till i-1 and print " " i.e., space
    • Then print "*" i.e., asterisk
    • Iterate on k from 0 till 2*t-1 and print " " i.e., space
    • Decrement t by 1.
  • Print " *" at the end of each iteration.

Below is the implementation of the above approach:


Output
* *
 * *
 * *
 * *
 * *
 * *
 * *
 *
 *
 *
 *
 *

Time Complexity: O(N2), for using nested loops.
Auxiliary Space: O(1), as constant extra space is required.

Comment
Article Tags: