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;
}
function pascalRow(n: number): number[] {
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;
}
def pascal_row(n: int) -> list[int]:
row = [1]
for _ in range(n):
row = [1] + [row[j - 1] + row[j] for j in range(1, len(row))] + [1]
return row
<?php
function pascalRow(int $n): array
{
$row = [1];
for ($i = 0; $i < $n; $i++) {
$next = [1];
for ($j = 1; $j < count($row); $j++) {
$next[] = $row[$j - 1] + $row[$j];
}
$next[] = 1;
$row = $next;
}
return $row;
}
class Solution {
public int[] pascalRow(int n) {
int[] row = new int[n + 1];
row[0] = 1;
for (int i = 1; i <= n; i++) for (int j = i; j > 0; j--) row[j] += row[j - 1];
return row;
}
}
More Basics problems
- Reverse a String · Easy
- Count the Vowels · Easy
- Capitalize Each Word · Easy
- Longest Word in a Sentence · Easy
- Run-Length Encoding · Easy
- Is It a Pangram? · Easy