Back to Freecodecamp

Challenge 230: Pascal's Triangle Row

curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69b1028d6e265413d0198a29.md

latest1.4 KB
Original Source

--description--

Given an integer n, return the nth row of Pascal's triangle as an array.

In Pascal's Triangle, each row begins and ends with 1, and each interior value is the sum of the two values directly above it.

Here's the first 5 rows of the triangle:

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

--hints--

pascalRow(5) should return [1, 4, 6, 4, 1].

js
assert.deepEqual(pascalRow(5), [1, 4, 6, 4, 1]);

pascalRow(3) should return [1, 2, 1].

js
assert.deepEqual(pascalRow(3), [1, 2, 1]);

pascalRow(1) should return [1].

js
assert.deepEqual(pascalRow(1), [1]);

pascalRow(10) should return [1, 9, 36, 84, 126, 126, 84, 36, 9, 1].

js
assert.deepEqual(pascalRow(10), [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]);

pascalRow(15) should return [1, 14, 91, 364, 1001, 2002, 3003, 3432, 3003, 2002, 1001, 364, 91, 14, 1].

js
assert.deepEqual(pascalRow(15), [1, 14, 91, 364, 1001, 2002, 3003, 3432, 3003, 2002, 1001, 364, 91, 14, 1]);

--seed--

--seed-contents--

js
function pascalRow(n) {

  return n;
}

--solutions--

js
function pascalRow(n) {
  if (n === 1) return [1];

  let row = [1];

  for (let i = 2; 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;
}