Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Finding the elements of nth row of Pascal's triangle in JavaScript
Pascal's triangle is a triangular array constructed by summing adjacent elements in preceding rows. Each row starts and ends with 1, and each interior element is the sum of the two elements above it.
The first few rows of Pascal's triangle are:
We need to write a JavaScript function that takes a positive number as input and returns an array containing all elements in that row of Pascal's triangle.
Example Input and Output
If the input is:
const num = 4;
The output should be the 4th row:
[1, 4, 6, 4, 1]
Solution
Here's an efficient approach that builds the nth row directly:
const num = 4;
const pascalRow = (n) => {
const row = [1]; // Start with first element
for (let i = 1; i <= n; i++) {
// Each element is previous element * (n - i + 1) / i
row[i] = row[i - 1] * (n - i + 1) / i;
}
return row;
};
console.log("Row", num + ":", pascalRow(num));
Row 4: [ 1, 4, 6, 4, 1 ]
Alternative Method: Building Row by Row
This method builds Pascal's triangle row by row until reaching the desired row:
const num = 4;
const pascalRowIterative = (n) => {
let row = [1];
for (let i = 0; i < n; i++) {
const newRow = [1];
for (let j = 1; j < row.length; j++) {
newRow[j] = row[j - 1] + row[j];
}
newRow.push(1);
row = newRow;
}
return row;
};
console.log("Row", num + ":", pascalRowIterative(num));
Row 4: [ 1, 4, 6, 4, 1 ]
Testing with Larger Row
Let's test with the 9th row as mentioned in the original problem:
const num = 9;
const pascalRow = (n) => {
const row = [1];
for (let i = 1; i <= n; i++) {
row[i] = row[i - 1] * (n - i + 1) / i;
}
return row;
};
console.log("Row", num + ":", pascalRow(num));
Row 9: [ 1, 9, 36, 84, 126, 126, 84, 36, 9, 1 ]
Comparison of Methods
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Direct Formula | O(n) | O(n) | Single row calculation |
| Iterative Build | O(n²) | O(n) | Understanding the pattern |
Conclusion
The direct formula method is more efficient for calculating a specific row in Pascal's triangle. Each element can be calculated using the binomial coefficient formula, making it faster than building the entire triangle.
