Tutorialspoint
Problem
Solution
Submissions

Pascal's Triangle

Certification: Basic Level Accuracy: 0% Submissions: 0 Points: 5

Write a JavaScript program to generate Pascal's Triangle with a given number of rows. Pascal's Triangle is a triangular array where each number is the sum of the two numbers directly above it, with 1s at the edges.

Example 1
  • Input: numRows = 5
  • Output: [[1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1]]
  • Explanation:
    • Row 0 contains [1]. Row 1 contains [1, 1] where edges are 1.
    • Row 2 contains [1, 2, 1] where middle element 2 = 1 + 1.
    • Row 3 contains [1, 3, 3, 1] where 3 = 1 + 2 and 3 = 2 + 1.
    • Row 4 contains [1, 4, 6, 4, 1] where elements are sum of above two.
Example 2
  • Input: numRows = 1
  • Output: [[1]]
  • Explanation:
    • With only 1 row, Pascal's Triangle contains just [1].
    • This is the base case of Pascal's Triangle.
Constraints
  • 1 ≤ numRows ≤ 30
  • Each row starts and ends with 1
  • Time Complexity: O(numRows^2)
  • Space Complexity: O(numRows^2) for storing the result
ArraysHCL TechnologiesApple
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Initialize the result array to store all rows of Pascal's Triangle
  • The first row always contains [1]
  • For each subsequent row, start and end with 1
  • Calculate middle elements by adding corresponding elements from the previous row
  • For row i, element at position j equals prevRow[j-1] + prevRow[j]
  • Each row has one more element than its row number (row i has i+1 elements)

Steps to solve by this approach:

 Step 1: Initialize an empty result array to store all rows of Pascal's Triangle.
 Step 2: Use an outer loop to iterate through each row from 0 to numRows-1.
 Step 3: For each row i, create a new array to store i+1 elements.
 Step 4: Use an inner loop to calculate each element in the current row.
 Step 5: Set first and last elements of each row to 1 (boundary condition).
 Step 6: For middle elements, sum the corresponding elements from the previous row: result[i-1][j-1] + result[i-1][j].
 Step 7: Add the completed row to the result array and return the final Pascal's Triangle.

Submitted Code :