DSA Tracker

Easy

Pascal's Triangle

An easy Arrays problem included in Striver A2Z. Below: the roles whose interviews prioritise this topic, and how to practise it.

Topic
Arrays
Sheets
1
Core for
25 roles
Platform
LeetCode

The problem

Generate the first n rows of Pascal's triangle, where each number is the sum of the two numbers directly above it.

Example 1

Input
n=5
Output
[[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]

Example 2

Input
n=1
Output
[[1]]

Example 3

Input
n=3
Output
[[1],[1,1],[1,2,1]]

Constraints

  • 1 <= n <= 30

How to think about it

Updated 2026-09-09

Every interior number is the sum of its two upper neighbors from the row above, while the edges are fixed at 1. Generating row by row lets each stage directly consume the values computed in the immediately preceding row without recalculating combinations from scratch.

Approaches, worst first

  1. Combinations formula

    time O(n^2) · space O(1)

    Compute each entry (r, c) independently using the formula nCr = r! / (c! * (r - c)!). Evaluating factorial terms independently does duplicate work across the triangle and risks severe arithmetic overflow for larger row indices.

  2. Iterative row constructionWrite this one

    time O(n^2) · space O(1)

    Initialize the first row with [1]. For each subsequent row, place 1 at both boundaries and fill each interior index j with prevRow[j - 1] + prevRow[j]. Each row requires only the previous row to assemble its values cleanly.

Where people lose marks · 3
  • Indexing prevRow out of bounds when attempting to add neighbors for the boundary elements at column 0 and column r.
  • Accidentally sharing row object references or mutating an earlier row in-place while reading it to construct the next.
  • Using 32-bit signed integers if computing nCr via factorials rather than iterative additions, since 30! massively exceeds integer capacity.

Full solution

Iterative row construction: each row starts as all 1s and every interior cell is the sum of the two cells above it in the previous row. No factorials, so nothing overflows and the edges never index out of bounds.

Python
def generate(n: int) -> list[list[int]]:
    rows: list[list[int]] = []
    for r in range(n):
        row = [1] * (r + 1)
        # Interior cells sum the two cells above; edges stay 1.
        for j in range(1, r):
            row[j] = rows[r - 1][j - 1] + rows[r - 1][j]
        rows.append(row)
    return rows
JavaScript
function generate(n) {
  const rows = [];
  for (let r = 0; r < n; r++) {
    const row = new Array(r + 1).fill(1);
    // Interior cells sum the two cells above; edges stay 1.
    for (let j = 1; j < r; j++) {
      row[j] = rows[r - 1][j - 1] + rows[r - 1][j];
    }
    rows.push(row);
  }
  return rows;
}
Try it in the editor

The theory behind it

Arrays — the ground this problem stands on. All Arrays problems

What Arrays is

An array is a row of fixed boxes laid side by side in computer memory, like numbered lockers in a hallway. Because each box occupies identical space and sits directly next to its neighbors, jumping to locker zero or locker ten thousand takes the exact same tiny fraction of time. Every box holds an item of the same type, addressed by an offset number called an index.

When to reach for it

Reach for an array when items arrive in a known sequence and need immediate retrieval by position number. Problems asking for running totals, prefix accumulations, cyclic rotations, or in-place rearrangements signal array mechanics. Whenever constraints require constant-time random lookups or contiguous cache scans across fixed collections, a flat sequence is the default container.

How the pattern works

Visualize a tape with zero-indexed slots stretching from start to end. Keep track of write and read cursors when modifying contents without allocating helper buffers. For running computations, maintain an invariant such as having processed all elements left of the current index while pending elements wait to the right. When modifying entries in place, consider scanning backwards from the end so unread data is not overwritten.

What each operation costs

OperationTime
look up element by indexO(1)
insert or delete at the startO(n)
search an unsorted collection for a valueO(n)
What usually goes wrong with Arrays
  • Reading past the final index by checking index less than or equal to length instead of strictly less than length, triggering index out of bounds exceptions.
  • Modifying length or removing elements during a forward iteration loop, which causes remaining items to shift left and skip validation on the next neighbor.
  • Assuming dynamic resizing is costless inside nested loops, causing repeated memory reallocation copies when appending unknown quantities of items.

Which roles need this problem

Arrays is a core topic for these 25 roles — if you're targeting one of them, this problem is early in your path, not optional.

Secondary for 3 more roles, including Database Engineer, Bioinformatics Engineer, Networking Engineer.

Track this in your role's order

Pick your target role and all 370 problems — including this one — resequence to what that interview actually asks. Free.

Start free

More Arrays problems

Problem set and role mapping as of .