AlgoInsight

DSA problem

Pascal's Triangle

Easy2D Grid DPPattern: 2D Grid DPtop600FreeAmazonMicrosoftGoogleAdobeApple

Given an integer numRows, return the first numRows of Pascal's triangle. Each row is a list of integers; the triangle as a whole is a list of lists, with row i containing exactly i + 1 entries.

Pascal's triangle is built by a simple geometric rule: every interior entry is the sum of the two entries directly above it in the previous row, while the first and last entries of every row are always 1. So row 0 is [1], row 1 is [1, 1], row 2 is [1, 2, 1], row 3 is [1, 3, 3, 1], and so on. The same numbers arise as binomial coefficients C(n, k), and they show up everywhere from combinatorics to probability to polynomial expansion.

A direct approach is to compute each entry as a binomial coefficient using factorials. That works for small inputs but quickly overflows for larger rows and recomputes the same factorials many times. It is also overkill: the recurrence C(n, k) = C(n - 1, k - 1) + C(n - 1, k) is exactly the row-by-row construction rule, so building the triangle is itself the natural DP.

The optimal approach treats each row as the result of a tiny 1-D DP over the previous row. Starting from [1], repeatedly build the next row by setting row[0] = row[-1] = 1 and row[j] = prev[j - 1] + prev[j] for the interior positions. This produces numRows rows in O(numRows^2) time and O(numRows^2) space (counting the output itself), with no overflow risk and only addition.

Examples

Example 1
Input: numRows = 5
Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
Explanation: Each row is built from the one above by summing adjacent entries and padding with 1s at the ends.
Example 2
Input: numRows = 1
Output: [[1]]
Explanation: The single requested row is the apex of the triangle.
Example 3
Input: numRows = 3
Output: [[1],[1,1],[1,2,1]]
Explanation: Row 2 has interior entry 2 = 1 + 1 from the row above.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

arraydynamic-programmingmath

Browse all DSA problems