1. Pascal Triangle
The problem can be found at the following link: ๐ Question Link
๐งฉ Problem Description
Given a positive integer n
, return the n
th row of Pascal's Triangle.
Pascal's Triangle is a triangular array where each element is the sum of the two elements directly above it in the previous row. The n
th row contains n
elements indexed from 0 to n-1
, and follows the binomial coefficient formula:
row[k] = C(n-1, k)
๐ Examples
Example 1:
Input:
n = 4
Output:
[1, 3, 3, 1]
Explanation:
The 4th row of Pascalโs Triangle is [1, 3, 3, 1]
.
Example 2:
Input:
n = 5
Output:
[1, 4, 6, 4, 1]
Explanation:
The 5th row of Pascalโs Triangle is [1, 4, 6, 4, 1]
.
Example 3:
Input:
n = 1
Output:
[1]
Explanation:
The 1st row of Pascalโs Triangle is [1]
.
๐ Constraints
$1 \leq n \leq 20$
โ
My Approach
Optimized Approach: Direct Binomial Formula
We use the mathematical identity:
C(n, k) = C(n, k - 1) * (n - k + 1) / k
$[ \text{row}[0] = 1,\quad \text{row}[i] = \text{row}[i-1] \times \frac{n-1 - (i-1)}{i}\quad \text{for } i=1,\dots,n-1 ]$
This builds the row in a single pass, using only integer arithmetic and avoiding overflow when $n\le20$.
Algorithm Steps:
Initialize result list
row = []
.Set variable
val = 1
(first element is always 1).For each index
k
from0
ton-1
:Append current
val
torow
.Compute next
val
as:val = val * (n - 1 - k) / (k + 1)
Return the
row
.
๐งฎ Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), as we compute each of the
n
elements once using constant-time math.Expected Auxiliary Space Complexity: O(n), as we store exactly
n
integers in the result list.
๐ง Code (C++)
class Solution {
public:
vector<int> nthRowOfPascalTriangle(int n) {
vector<int> row(n);
row[0]=1;
for(int i=1;i<n;++i) row[i]=row[i-1]*(n-i)/i;
return row;
}
};
๐งโ๐ป Code (Java)
class Solution {
public ArrayList<Integer> nthRowOfPascalTriangle(int n) {
ArrayList<Integer> row=new ArrayList<>();
long v=1;
for(int i=0;i<n;++i){
row.add((int)v);
v=v*(n-1-i)/(i+1);
}
return row;
}
}
๐ Code (Python)
class Solution:
def nthRowOfPascalTriangle(self, n):
row, v = [], 1
for i in range(n):
row.append(v)
v = v * (n-1-i) // (i+1)
return row
๐ง Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: ๐ฌ Any Questions?. Letโs make this learning journey more collaborative!
โญ If you find this helpful, please give this repository a star! โญ
๐Visitor Count
Last updated