Pascal's Triangle - Problem
Pascal's Triangle is one of the most beautiful mathematical constructs! Your task is to generate the first numRows rows of Pascal's Triangle.

In Pascal's Triangle, each row starts and ends with 1, and every other number is the sum of the two numbers directly above it from the previous row. This creates a triangular pattern where each number represents a binomial coefficient.

Example: If numRows = 5, you should return:
    1
   1 1
  1 2 1
 1 3 3 1
1 4 6 4 1

šŸŽÆ Goal: Return a 2D array where each inner array represents a row of Pascal's Triangle.
šŸ“„ Input: An integer numRows (1 ≤ numRows ≤ 30)
šŸ“¤ Output: A 2D array containing the first numRows of Pascal's Triangle

Input & Output

example_1.py — Basic Triangle
$ Input: numRows = 5
› Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
šŸ’” Note: The first 5 rows of Pascal's Triangle. Each number is the sum of the two numbers above it. Row 0 has [1], Row 1 has [1,1], Row 2 has [1,2,1] where 2 = 1+1, and so on.
example_2.py — Single Row
$ Input: numRows = 1
› Output: [[1]]
šŸ’” Note: When numRows is 1, we only return the first row of Pascal's Triangle, which contains just the number 1.
example_3.py — Small Triangle
$ Input: numRows = 3
› Output: [[1],[1,1],[1,2,1]]
šŸ’” Note: The first 3 rows show the basic pattern: edges are always 1, and middle elements are sums of the pair above (1+1=2 in the third row).

Visualization

Tap to expand
Pascal's Triangle - The Addition Pattern1111211331146411+1=21+2=32+1=3The Beautiful PatternšŸ”“ Red triangles: Always 1 (edges of the triangle)šŸ”µ Blue/Orange triangles: Sum of the two triangles directly above them
Understanding the Visualization
1
Foundation
Place the first block with value 1 at the top
2
Second Level
Place two blocks with value 1 each, supported by the first block
3
Pattern Formation
Each new level starts and ends with 1
4
Addition Rule
Interior blocks get the sum of their two supporting blocks
Key Takeaway
šŸŽÆ Key Insight: Pascal's Triangle naturally builds itself row by row using simple addition - no complex formulas needed!

Time & Space Complexity

Time Complexity
ā±ļø
O(n³)

For each of the n² elements, we calculate factorials which take O(n) time in the worst case

n
2n
⚠ Quadratic Growth
Space Complexity
O(n²)

We store the entire triangle which has n² elements in total

n
2n
⚠ Quadratic Space

Constraints

  • 1 ≤ numRows ≤ 30
  • All elements will fit in a 32-bit integer
  • Note: The triangle grows quadratically in size
Asked in
Google 42 Amazon 35 Microsoft 28 Apple 22
95.4K Views
High Frequency
~15 min Avg. Time
2.8K Likes
Ln 1, Col 1
Smart Actions
šŸ’” Explanation
AI Ready
šŸ’” Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen