Last Updated: March 31, 2026
We need to build Pascal's triangle row by row. Each row starts and ends with 1, and every element in between is the sum of the two elements directly above it from the previous row.
The structure is straightforward once you see it. Row 0 is just [1]. Row 1 is [1, 1]. For row 2, the edges are 1, and the middle element is 1 + 1 = 2, giving [1, 2, 1]. Row 3 takes the middle values from row 2: 1 + 2 = 3 and 2 + 1 = 3, producing [1, 3, 3, 1].
The key observation is that row i has exactly i + 1 elements, and element j in row i (where j is not the first or last) equals row[i-1][j-1] + row[i-1][j]. This dependency on the previous row is what drives the solution.
1 <= numRows <= 30 → With numRows at most 30, the total number of elements is at most 465. Even an O(n^3) approach would be trivially fast. There is no performance pressure here.The most natural way to build Pascal's triangle is exactly how you'd draw it by hand. Start with the first row [1], then generate each subsequent row using the one before it.
For each new row, we know the first and last elements are always 1. For everything in the middle, we just look up at the previous row and add the two numbers that sit above and to the left. That's it. No fancy algorithms needed, just a nested loop.
[[1]].i from 1 to numRows - 1:[1].j from 1 to i - 1, compute the value as previousRow[j-1] + previousRow[j] and append it.This approach is already optimal in terms of time complexity, since we must produce every element in the triangle. But there's an alternative way to compute each row using a mathematical formula, without referencing the previous row at all.
Every element in Pascal's triangle is a binomial coefficient. Specifically, element j in row i equals C(i, j) = i! / (j! * (i-j)!).
But computing factorials directly would be wasteful and risk overflow. There's a much cleaner trick. Once you know one element in a row, you can get the next one with a simple multiplication and division:
C(i, j) = C(i, j-1) * (i - j + 1) / j
So we can generate each row by starting with 1 (since C(i, 0) = 1) and then multiplying by a ratio to get the next element. No need to look at the previous row at all.
The binomial coefficient identity C(n, k) = C(n, k-1) * (n-k+1) / k comes from expanding the factorial formula. If you divide C(n, k) by C(n, k-1), the factorials mostly cancel out, leaving (n-k+1)/k. This means once you have any element in the row, multiplying by this ratio gives you the next one. Starting from C(n, 0) = 1, we can chain these multiplications across the entire row.
i from 0 to numRows - 1:[1].j from 1 to i, compute the next value as previousValue * (i - j + 1) / j.