Program to print the diamond pattern

Learn how to print the diamond pattern in javascript.

Example

"    *    "
"   ***   "
"  *****  "
" ******* "
"*********"
" ******* "
"  *****  "
"   ***   "
"    *    "

Implementation

Implementing an algorithm to print the diamond pattern may seem complicated but it is fairly simple. It is just like printing two pyramids in opposite direction.

  • We will use 8 different loops to print the diamond pattern.
  • These loops will be divided in two different sections.
  • One will print the pyramid from top to bottom and second will print it from bottom to top.
  • Each section will have an loop with three loops nested in it.
  • The first nested loop will add white space on left, the second loop will add the '*' and the last loop will add the white space on the right.
let diamondPattern = (rows) => {
   
   //Print first half of the diamond
   for(let i = 1; i <= rows; i++){
     let str = '';
     
     //Add the white space to the left
     for(let k = 1; k <= (rows - i); k++){
       str += ' ';
     }
     
     //Add the '*' for each row
     for(let j = 0; j != (2 * i - 1); j++){
       str += '*';
     }
     
     //Add the white space to the right
     for(let k =  i + 1; k <= rows; k++){
       str += ' ';
     }
     
      //Print the pyramid pattern for each row
     console.log(str);
   }
   
   //Print the second half of the diamond
   for(let i = rows - 1; i >= 1; i--){
     let str = '';
     
     //Add the white space to the left
     for(let k = 1; k <= (rows - i); k++){
       str += ' ';
     }
     
     //Add the '*' for each row
     for(let j = 0; j != (2 * i - 1); j++){
       str += '*';
     }
     
     //Add the white space to the right
     for(let k =  i + 1; k <= rows; k++){
       str += ' ';
     }
     
      //Print the pyramid pattern for each row
     console.log(str);
   }
}
Input:
diamondPattern(5);

Output:
"    *    "
"   ***   "
"  *****  "
" ******* "
"*********"
" ******* "
"  *****  "
"   ***   "
"    *    "

Time complexity: O(n ^ 2).
Space complexity: O(1).

Time and Space complexity

  • We are printing the each row of the pyramid by using three different loops which will take O(n) and we are doing this for n times so it is O(n * n) = O(n ^ 2). Now we are printing the pyramids in two different sections to make it diamond so O(n ^ 2) + O(n ^ 2) = O(2(n ^ 2)) = O(n ^ 2).
  • We are using constant space, so Space complexity is O(1).