Pascal's Triangle II - Problem

Given an integer rowIndex, return the rowIndex-th (0-indexed) row 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 subsequent row begins and ends with 1.

Example: Row 0: [1], Row 1: [1,1], Row 2: [1,2,1], Row 3: [1,3,3,1]

Input & Output

Example 1 — Row 3
$ Input: rowIndex = 3
Output: [1,3,3,1]
💡 Note: Row 3 of Pascal's triangle: The 4th row (0-indexed) contains the values [1,3,3,1], where each inner element is the sum of the two elements above it from the previous row.
Example 2 — Row 0
$ Input: rowIndex = 0
Output: [1]
💡 Note: Row 0 is the first row of Pascal's triangle and contains only the value 1.
Example 3 — Row 1
$ Input: rowIndex = 1
Output: [1,1]
💡 Note: Row 1 contains [1,1] - two 1s at the edges as every row starts and ends with 1.

Constraints

  • 0 ≤ rowIndex ≤ 33

Visualization

Tap to expand
Pascal's Triangle II - Space Optimized INPUT Pascal's Triangle Structure 1 1 1 1 2 1 1 3 3 1 Target: Row 3 (0-indexed) Input Parameter rowIndex = 3 Using two arrays: prev[] and curr[] prev[] curr[] ALGORITHM STEPS 1 Initialize Arrays prev = [1], curr = [] 2 Loop Rows 1 to 3 Build each row iteratively 3 Compute Current Row curr[j] = prev[j-1] + prev[j] 4 Swap Arrays prev = curr, continue Iterations: i=1: prev=[1] curr=[1,1] i=2: prev=[1,1] curr=[1,2,1] i=3: prev=[1,2,1] curr=[1,3,3,1] FINAL RESULT Row 3 of Pascal's Triangle 1 [0] 3 [1] 3 [2] 1 [3] Output [1, 3, 3, 1] OK - Verified! Complexity Analysis Time: O(rowIndex^2) Space: O(rowIndex) Only 2 arrays of size n Key Insight: The two-array approach uses only O(n) space by maintaining just the previous and current rows. Each element curr[j] = prev[j-1] + prev[j] computes the sum of two elements directly above. After each row, we swap: prev becomes curr, avoiding O(n^2) storage of the entire triangle. TutorialsPoint - Pascal's Triangle II | Space Optimized - Two Arrays Approach
Asked in
Apple 15 Microsoft 12
155.4K Views
Medium Frequency
~15 min Avg. Time
4.2K 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