Coding problem · Easy · Basics

Pascal's Triangle Row

Easy Algorithms & data structures

Return row n (starting from 0) of Pascal's triangle. Each row starts and ends with 1, and every other value is the sum of the two values above it.

row 0:     1
row 1:    1 1
row 2:   1 2 1
row 3:  1 3 3 1

Example 1

Input: n = 3
Output: [1,3,3,1]

Example 2

Input: n = 0
Output: [1]

Hints

Hint 1

Build each row from the previous one.

Hint 2

New row: 1, then prev[i-1] + prev[i] for the middle, then 1.

Write and run your solution

Loading the editor… (JavaScript is required to run code in your browser.)

Solution and explanation

Show the solution

Time O(n²) · Space O(n)

Start from [1] and build n times: each new row is 1, the pairwise sums of the previous row, then 1.

Reference solution

function pascalRow(n) {
  let row = [1];
  for (let i = 0; i < n; i++) {
    const next = [1];
    for (let j = 1; j < row.length; j++) next.push(row[j - 1] + row[j]);
    next.push(1);
    row = next;
  }
  return row;
}

Was this page helpful?