Pascal's Triangle II
Pattern: Matrix traversal
One row of Pascal's triangle, without building the rows above it. The value at column c is C(n, c), and each value comes from the one before it with one multiply and one exact divide.
The problem
Given rowIndex, return that row of Pascal's triangle, counting rows from 0. For example, rowIndex = 3 gives
[1, 3, 3, 1], rowIndex = 0 gives [1], and rowIndex = 1 gives [1, 1].
The function name getRow matches LeetCode. Use the link above for the exact statement and limits. LeetCode also asks
whether you can use only O(rowIndex) extra memory, and this method does.
Think first
- Which binomial number sits at row
n, columnc? - How does
C(n, c + 1)relate toC(n, c)? - Why must you multiply before you divide?
Hints
Brute force, and why it fails
Build every row from the top as in Pascal's Triangle, keeping only the last one: O(n²) time and O(n) memory. A single list updated from right to left also works in O(n²). The formula gives the row in O(n).
The key insight
Neighbouring values in one row differ by the factor (n - c) / (c + 1). Starting from 1, the whole row follows in one
left-to-right walk.
Dry run
| c | 0 |
|---|---|
| value | 1 |
rowIndex = 4. The first value is C(4, 0) = 1.
The plan
row = empty list
value = 1
for c from 0 to n:
add value to row
value = value * (n - c) / (c + 1)
return row
Complexity
- Time
O(n)- Space
O(n)
One step per value, and the row is the only thing stored.
Edge cases
rowIndex = 0:[1].- The last step computes
value × 0, which is fine and never added. - The middle of row 33 is 1,166,803,110, which fits in a 32-bit number, but the product before dividing does not.
I've built my logic, show the code
Java
import java.util.*;
class Solution {
public List<Integer> getRow(int rowIndex) {
List<Integer> row = new ArrayList<>();
long value = 1; // C(rowIndex, 0)
for (int c = 0; c <= rowIndex; c++) {
row.add((int) value);
value = value * (rowIndex - c) / (c + 1); // C(n, c + 1) from C(n, c)
}
return row;
}
}C++
class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> row;
long long value = 1; // C(rowIndex, 0)
for (int c = 0; c <= rowIndex; c++) {
row.push_back(static_cast<int>(value));
value = value * (rowIndex - c) / (c + 1); // C(n, c + 1) from C(n, c)
}
return row;
}
};Python
class Solution:
def getRow(self, rowIndex: int) -> list[int]:
row = []
value = 1 # C(rowIndex, 0)
for c in range(rowIndex + 1):
row.append(value)
value = value * (rowIndex - c) // (c + 1) # C(n, c + 1) from C(n, c)
return rowCommon mistakes
- Writing
value * ((n - c) / (c + 1)), which divides first and rounds down too early. - Keeping
valueas a 32-bit number, sovalue × (n - c)overflows near the middle of large rows. - Returning
rowIndexvalues instead ofrowIndex + 1.