JavaScript Program to Print the Nth Row of Pascal’s Triangle
Pascal’s triangle is a triangular array of binomial coefficients. Each number in the triangle is the sum of the two directly above it.
Given a non-negative integer N, the task is to find the Nth row of Pascal’s Triangle.
Table of Content
- Using Binomial Coefficient Formula
- Using Recursion
Using Binomial Coefficient Formula
This approach relies on the binomial coefficient formula to compute the value of each element in the nth row of Pascal’s triangle. The binomial coefficient formula calculates the number of ways to choose k elements from a set of n elements denoted as “C(n, k)”.
The formula for binomial coefficient is:
C(n, k) = n! / (k! * (n - k)!)
Example: This example prints the n-th row of Pascal’s triangle using binomial coefficient formula.
function pascalsRow(n) {
let row = [];
for (let i = 0; i <= n; i++) {
row.push(binomial(n, i));
}
return row;
}
function binomial(n, k) {
let result = 1;
for (let i = 1; i <= k; i++) {
result *= (n - i + 1) / i;
}
return result;
}
console.log(pascalsRow(3));
Output
[ 1, 3, 3, 1 ]
Time Complexity: O(N2)
Space Complexity: O(N)
Using Recursion
This approach uses recursion to generate the nth row of Pascal’s triangle. Here each element in a row (except the first and last elements which are always 1) is computed by summing the two elements diagonally above it in the previous row.
Example: This example uses recursion to print the n-th row of Pascal’s triangle.
function pascalsRow(n) {
if (n === 0) return [1];
if (n === 1) return [1, 1];
let prev = pascalsRow(n - 1);
let row = [1];
for (let i = 1; i < prev.length; i++) {
row.push(prev[i - 1] + prev[i]);
}
row.push(1);
return row;
}
console.log(pascalsRow(4));
Output
[ 1, 4, 6, 4, 1 ]
Time Complexity: O(2n) due to recursion
Space Complexity: O(n)
Contact Us