Pascal's Triangle - Problem

Given an integer numRows, return the first numRows of Pascal's triangle.

In Pascal's triangle, each number is the sum of the two numbers directly above it. The triangle starts with 1 at the top, and each row begins and ends with 1.

Example: For numRows = 5, the triangle looks like:

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

Input & Output

Example 1 — Basic Triangle
$ Input: numRows = 5
Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
💡 Note: First 5 rows of Pascal's triangle. Row 0 is [1], Row 1 is [1,1], Row 2 is [1,2,1] where 2=1+1, Row 3 is [1,3,3,1] where 3=1+2, and Row 4 is [1,4,6,4,1] where 4=1+3 and 6=3+3.
Example 2 — Small Triangle
$ Input: numRows = 1
Output: [[1]]
💡 Note: Only the top of the triangle with just one element: 1
Example 3 — Two Rows
$ Input: numRows = 2
Output: [[1],[1,1]]
💡 Note: First two rows: the top [1] and second row [1,1]

Constraints

  • 1 ≤ numRows ≤ 30

Visualization

Tap to expand
Pascal's Triangle - Space-Optimized Construction INPUT numRows = 5 Goal: Build triangle Row 0: ? Row 1: ? ? Row 2: ? ? ? Row 3: ? ? ? ? Row 4: ? ? ? ? ? Each number = sum of two numbers above it Edges are always 1 ALGORITHM STEPS 1 Initialize Result result = [[1]] 2 Loop rows 1 to n-1 for i in range(1, numRows) 3 Build each row Start/end with 1 4 Calculate middle row[j] = prev[j-1] + prev[j] Example: Building Row 3 prev = [1, 2, 1] new[0] = 1 new[1] = 1+2 = 3 new[2] = 2+1 = 3 new[3] = 1 Result: [1,3,3,1] FINAL RESULT Pascal's Triangle 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 [[1],[1,1],[1,2,1], [1,3,3,1],[1,4,6,4,1]] 5 Rows - OK Key Insight: Space-optimized approach uses only the previous row to compute the current row. Time: O(n^2) - we fill n*(n+1)/2 cells. Space: O(n) - only need to store previous row during computation. Each row[j] = row[j-1] * (row_num - j + 1) / j can also compute values using binomial coefficients. TutorialsPoint - Pascal's Triangle | Space-Optimized Construction
Asked in
Apple 15 Microsoft 12 Google 8 Amazon 6
125.0K Views
Medium Frequency
~15 min Avg. Time
2.9K 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