Pascal's Triangle

easy

Given an integer numRows, build the first numRows rows of Pascal's triangle and return them.

Pascal's triangle starts with a single 1 at the top. Every entry below is the sum of the two entries directly above it; where there is only one entry above (the left and right edges), the value is always 1.

Return the triangle as a list of rows, where row i (0-indexed) contains i + 1 numbers.

Hints

You're not asked for a single value — you must output the whole triangle, row by row. How does a brand-new row relate to the row right before it?
The first and last entry of every row are always 1. Only the interior entries need work — and each of those is a sum of two neighbours one row up.
Set row[j] = prev[j-1] + prev[j]. Or, if you know combinatorics, row i entry k is C(i, k), which you can scale from its left neighbour with (i-k+1)/k.

Common doubts

Those edge cells have only one cell above them (there's no second parent off the side), so they inherit that single 1 straight down from the apex.
The judge normalises each row (sorts it) and then sorts the rows, so any correct triangle passes regardless of internal ordering. Focus on producing the right values.
For numRows <= 30 the largest value is C(29, 14) = 67863915, well within a 32-bit int. The multiplicative method multiplies before dividing, so intermediate products stay small too.

Interview follow-ups

Yes — that's the "single row in O(k) space" variant. Keep one array and update it in place from right to left, or use the C(k, j) scaling trick to emit one row without building the others.
The output itself is O(n²), so that cost is unavoidable, but you can stream rows one at a time and, if only specific entries are needed, compute them modulo a prime using precomputed factorials.

Fun facts

  • The diagonals of Pascal's triangle hide famous sequences: the third diagonal is the triangular numbers 1, 3, 6, 10…, and the shallow diagonals sum to the Fibonacci numbers.
  • Colour every odd entry and the Sierpiński triangle appears — the same fractal shows up in cellular automata and the Chaos Game.

Asked at

AmazonMicrosoftGoogleAdobe
Frequently Sometimes Occasionally
Example 1
Input: numRows = 5
Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
Each interior number is the sum of the two above it: 2 = 1+1, 3 = 1+2, 6 = 3+3.
Example 2
Input: numRows = 1
Output: [[1]]
Just the apex of the triangle.
Constraints

- 1 <= numRows <= 30

Solve this problem →