Pascal's Triangle (LeetCode 118): Solution and Explanation
Given a number of rows, produce that many rows of Pascal's triangle. Each row starts and ends with 1, and every value in between is the sum of the two values directly above it in the previous row.
Watch it run step by step
Try your own input and write the code →Intuition
One way to fill the triangle is with the closed formula: the value at row i, position j is the binomial coefficient C(i, j). Computing each coefficient from factorials is wasteful, though, and factorials grow so fast that they overflow fixed-width integers long before the values in the triangle do.
The definition of the triangle already describes a much simpler process. Each row depends only on the row before it, and each inner value is the sum of two neighbors above. That is a dynamic programming recurrence: row[j] = prev[j - 1] + prev[j]. The edges are fixed at 1, because there is only one value above them to draw from.
So build the triangle from the top down. Create each new row already filled with 1s, which takes care of both ends for free, and then overwrite the inner positions 1 through i - 1 using the row you just finished. Rows 0 and 1 have no inner positions, so the inner loop simply does not run for them, and they stay as [1] and [1,1].
Because every value is built from earlier ones that are already stored in triangle, each value takes a single addition, and the whole triangle is produced with no recomputation.
Approach: Row-by-row dynamic programming
- Start with an empty list
triangle. - For each row index
ifrom 0 tonumRows - 1, createrow = [1] * (i + 1), which sets both ends to 1. - For each inner index
jfrom 1 toi - 1, setrow[j] = triangle[i-1][j-1] + triangle[i-1][j]. - Append the finished row to
triangle. - After the last row, return
triangle.
Step-by-step example
numRows = 5
- Row 0 is [1]. It has no inner positions.
- Row 1 is [1,1]. The inner loop runs from 1 to 0, so it does nothing.
- Row 2 starts as [1,1,1]. Position 1 becomes 1 + 1 = 2, giving [1,2,1].
- Row 3 starts as [1,1,1,1]. Position 1 becomes 1 + 2 = 3 and position 2 becomes 2 + 1 = 3, giving [1,3,3,1].
- Row 4 fills positions 1 to 3 with 1 + 3 = 4, 3 + 3 = 6 and 3 + 1 = 4, giving [1,4,6,4,1].
- The result is [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]].
Code: Python, Java, C++
1class Solution:
2 def generate(self, numRows: int) -> List[List[int]]:
3 triangle = []
4
5 for i in range(numRows):
6 row = [1] * (i + 1) # Initialize with 1s
7
8 # Fill middle elements
9 for j in range(1, i):
10 row[j] = triangle[i-1][j-1] + triangle[i-1][j]
11
12 triangle.append(row)
13
14 return triangle1class Solution {
2 public List<List<Integer>> generate(int numRows) {
3 List<List<Integer>> triangle = new ArrayList<>();
4
5 for (int i = 0; i < numRows; i++) {
6 List<Integer> row = new ArrayList<>();
7 for (int j = 0; j <= i; j++) {
8 if (j == 0 || j == i) {
9 row.add(1);
10 } else {
11 row.add(triangle.get(i-1).get(j-1) + triangle.get(i-1).get(j));
12 }
13 }
14 triangle.add(row);
15 }
16
17 return triangle;
18 }
19}1class Solution {
2public:
3 vector<vector<int>> generate(int numRows) {
4 vector<vector<int>> triangle;
5
6 for (int i = 0; i < numRows; i++) {
7 vector<int> row(i + 1, 1);
8
9 for (int j = 1; j < i; j++) {
10 row[j] = triangle[i-1][j-1] + triangle[i-1][j];
11 }
12
13 triangle.push_back(row);
14 }
15
16 return triangle;
17 }
18};Time and space complexity
O(n²)
Row i has i + 1 values, each computed with one addition, so the total work is 1 + 2 + up to n, which is about n² / 2.
O(n²)
The output itself holds about n² / 2 numbers. Apart from the output, only the current row is being built, so the extra space is O(n).
Other approaches
Binomial coefficients per row (time O(n²), space O(n²))
Compute each row directly with the multiplicative rule C(i, j) = C(i, j - 1) × (i - j + 1) / j, starting from 1. Each row is independent of the previous one, which is handy for producing a single row, and integer division stays exact if you multiply before dividing.
Pad and add (time O(n²), space O(n²))
Build the next row by adding the previous row shifted left and shifted right, for example [a + b for a, b in zip([0] + prev, prev + [0])]. It is a compact one-liner per row with the same complexity.
Common mistakes
- Looping the inner index up to
iinstead ofi - 1, which overwrites the final 1 and readstriangle[i-1][i], an index that does not exist. - Reading from the current row instead of the previous one, such as
row[j - 1] + row[j], which uses values that are still all 1s. - Creating rows with
[[1] * n] * numRowsor appending the same list object repeatedly, so every row in the output points to the same list. - Computing factorials for each entry. Besides being slower, factorials overflow 32-bit integers around 13!, while the triangle's values stay small for the allowed row counts.
Frequently asked questions
How is each number in Pascal's triangle calculated?
Each inner number is the sum of the two numbers directly above it, and the first and last numbers in every row are 1. In code that is row[j] = prev[j - 1] + prev[j].
What is the time complexity of generating Pascal's triangle?
O(n²) for n rows, because the rows contain 1 + 2 + up to n numbers in total and each is computed with one addition. You cannot do better, since the output itself has that many numbers.
Is Pascal's Triangle a dynamic programming problem?
Yes, in a simple form. Each row is built from stored results of the previous row instead of being recomputed, which is the core idea of bottom-up dynamic programming.