Program to print the pascal triangle patterns

Learn how to print the pascal triangle patterns in javascript.

Example

"     1      "
"    1 1     "
"   1 2 1    "
"  1 3 3 1   "
" 1 4 6 4 1  "

Implementation

To print the pascal triangle in pyramid pattern, we will add white space to the left and the right and use a formula to generate the numbers.

  • We will use four loops to print the triangle in pyramid shape.
  • There will be a main loop which will be printing the each row and the three inner loops will generate the numbers.
  • First loop will add white space on the left, the second loop will generate the numbers with the formula number = number * (i - j) / (j + 1); and the third loop will add the white space on right.
let pascalTriangle = (rows) => {
  
   for(let i = 0; i < rows; i++){
     let str = '';
     let number = 1;
     
     //Add the white space to the left
     for(let k = 1; k <= (rows - i); k++){
       str += ' ';
     }
     
     //Add the numbers sequence for each row
     for(let j = 0; j <= i; j++){
       str += number + ' ';  
       
       //Formula to calculate the pascal triangle
       number = number * (i - j) / (j + 1);
     }
     
     //Add the white space to the right
     for(let k =  i + 1; k <= rows; k++){
       str += ' ';
     }
     
      //Print the pattern for each row
     console.log(str);
   }
   
}
Input:
pascalTriangle(5);

Output:
"     1      "
"    1 1     "
"   1 2 1    "
"  1 3 3 1   "
" 1 4 6 4 1  "

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

Time and Space complexity

  • It will take O(n) to generate the pascal triangle patterns with inner loops and we will be doing this for each row, So time complexity is O(n * n) = O(n ^ 2).
  • We are using constant space, so Space complexity is O(1).