The Pascal's Triangle II problem asks you to return the rowIndex
-th (0-indexed) row of Pascal's Triangle as a list of integers.
Pascal's Triangle is a triangular array where each number is the sum of the two numbers directly above it. The first row is [1]
, the second row is [1,1]
, the third row is [1,2,1]
, and so on.
rowIndex
.rowIndex
of Pascal's Triangle.rowIndex
≤ 33The most straightforward way to solve this would be to generate the entire Pascal's Triangle up to the given row and then return the required row. However, this is inefficient since we only need one row.
Recognizing the pattern, each value in a row is the sum of two values from the previous row. However, we can optimize memory usage by building only one row at a time and updating it in place, moving from the end of the row to the beginning to avoid overwriting values we still need.
Alternatively, since each element in the row is a binomial coefficient, we could compute each value directly using the formula C(rowIndex, k)
for each k
from 0
to rowIndex
.
1
(the first row).1
at the end (since each row starts and ends with 1).C(n, k) = C(n, k-1) * (n-k+1) / k
to iteratively compute each element.1
, then repeatedly compute the next value using the previous one.rowIndex
values.class Solution:
def getRow(self, rowIndex: int) -> list[int]:
row = [1]
for i in range(1, rowIndex + 1):
row.append(1)
for j in range(i - 1, 0, -1):
row[j] += row[j - 1]
return row
class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> row = {1};
for (int i = 1; i <= rowIndex; ++i) {
row.push_back(1);
for (int j = i - 1; j > 0; --j) {
row[j] += row[j - 1];
}
}
return row;
}
};
class Solution {
public List<Integer> getRow(int rowIndex) {
List<Integer> row = new ArrayList<>();
row.add(1);
for (int i = 1; i <= rowIndex; i++) {
row.add(1);
for (int j = i - 1; j > 0; j--) {
row.set(j, row.get(j) + row.get(j - 1));
}
}
return row;
}
}
var getRow = function(rowIndex) {
let row = [1];
for (let i = 1; i <= rowIndex; i++) {
row.push(1);
for (let j = i - 1; j > 0; j--) {
row[j] += row[j - 1];
}
}
return row;
};
Let's walk through an example with rowIndex = 3
:
row = [1]
i = 1
): append 1 → [1, 1]
i = 2
): append 1 → [1, 1, 1]
row[1] += row[0]
→ row[1] = 2
→ [1, 2, 1]
i = 3
): append 1 → [1, 2, 1, 1]
row[2] += row[1]
→ row[2] = 3
row[1] += row[0]
→ row[1] = 3
[1, 3, 3, 1]
Final output for rowIndex = 3
is [1, 3, 3, 1]
.
rowIndex
.
For rowIndex ≤ 33
, all approaches are efficient, but the in-place or binomial methods are most elegant.
The key insight is that we can build Pascal's Triangle rows efficiently by updating a single list in place, moving from the end to the start to avoid overwriting values. Alternatively, using the binomial coefficient formula lets us compute each value directly. Both approaches are optimal for this problem, using O(n) space and efficient time. This solution highlights how understanding the underlying mathematical structure can greatly simplify the implementation.