Pascal's Triangle II — Solution in Python, Java & C++
Pascal's Triangle II solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem.
Pascal's Triangle II is an easy coding problem on arrays and dynamic programming, asked in Amazon, Adobe and TCS interviews.
- Difficulty: Easy
- Topics: Arrays, Dynamic Programming
- Asked at: Amazon, Adobe, TCS
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
Given an integer rowIndex, return the rowIndex-th (0-indexed) row of Pascal's triangle.
Each number in the triangle is the sum of the two directly above it.
Example 1
Input: rowIndex = 3
Output: [1,3,3,1]
Example 2
Input: rowIndex = 0
Output: [1]
Example 3
Input: rowIndex = 4
Output: [1,4,6,4,1]
Constraints
0 <= rowIndex <= 30Every value fits in a signed 32-bit integer.
Follow-up: Can you build the row using only O(rowIndex) extra space?
Hints for Pascal's Triangle II
Hint 1
Building the whole triangle costs O(n²) space; only the previous row is ever needed.
Hint 2
Update one array in place, walking right to left so a slot is read before it is overwritten.
Hint 3
The closed form also works: each entry is the previous one times
(n - i + 1) / i.
How to solve Pascal's Triangle II
Only the previous row is needed; update a single array in place from right to left so each slot is read before it is overwritten.
Approach
- Start with
row = [1] * (rowIndex + 1). - For
ifrom 1 torowIndex, forjfromi - 1down to 1, setrow[j] += row[j-1]. - Return
row.
Why it works
Row i of the triangle is row i - 1 with each interior entry replaced by the sum of the two above it. Walking right to left guarantees row[j-1] is still the old value when row[j] is updated.
Complexity
- Time —
O(n²) - Space —
O(n)
Pitfalls
- Left-to-right updating uses already-updated neighbours and corrupts the row.
- The multiplicative closed form
row[i] = row[i-1] · (n - i + 1) / igives O(n).
Reference solution
Python
def getRow(rowIndex: int):
row = [1] * (rowIndex + 1)
for i in range(1, rowIndex + 1):
for j in range(i - 1, 0, -1):
row[j] += row[j - 1]
return rowJava
public static int[] getRow(int rowIndex) {
int[] row = new int[rowIndex + 1];
Arrays.fill(row, 1);
for (int i = 1; i <= rowIndex; i++) {
for (int j = i - 1; j > 0; j--) row[j] += row[j - 1];
}
return row;
}C++
vector<int> getRow(int rowIndex) {
vector<int> row(rowIndex + 1, 1);
for (int i = 1; i <= rowIndex; i++) {
for (int j = i - 1; j > 0; j--) row[j] += row[j - 1];
}
return row;
}JavaScript
var getRow = function(rowIndex) {
const row = new Array(rowIndex + 1).fill(1);
for (let i = 1; i <= rowIndex; i++) {
for (let j = i - 1; j > 0; j--) {
row[j] += row[j - 1];
}
}
return row;
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.
All 1199 arrays problems · the whole catalogue
Learn the technique: Arrays · Dynamic Programming