
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.
- Row 0 contains [1]. Row 1 contains [1, 1] where edges are 1.
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.
- With only 1 row, Pascal's Triangle contains just [1].
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
Editorial
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. |
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)