We use cookies for site analytics. Accept to help us understand how the site is used. See our Privacy Policy for details.
An easy dynamic programming problem, graded against 6 test cases (3 of them hidden).
Overlapping subproblems solved once and reused - the pattern candidates fear most.
Reach for it when you see: "Number of ways", "minimum/maximum cost", or a recursion that recomputes the same state.
More Dynamic Programmingproblems →Every entry is defined by entries already computed, and each row depends only on the row above it. That is dynamic programming in its most stripped-down form: a recurrence, evaluated bottom-up, with no memoization table beyond what you are already building.
Build row by row. Row `i` has `i + 1` entries; the ends are `1`, and interior entry `j` is `previous[j - 1] + previous[j]`. Because you always have the previous row in hand, no recursion or lookup structure is needed.
It is worth recognizing what the triangle contains, since interviewers often follow up: row `n` holds the binomial coefficients C(n, k), so entry (n, k) is also the number of ways to choose k items from n. That gives an O(k) direct formula for a single entry using the multiplicative identity - the right answer when asked for one row rather than all of them, which is a genuinely different problem ("Pascal's Triangle II") solvable in O(k) space.
The values grow quickly - row 30 already exceeds 10^8 - which is why the constraint stops there.
The full reference solution in every supported language stays in the editor above - reveal it there once you have had a real attempt.
These apply to the pattern as a whole, not just this problem.