DSA Tracker

Problem

Easy

Pascal's Triangle

An easy Arrays interview guide. Task statement, worked examples, intuition, and step-by-step solutions.

Topic
Arrays
Sheets
1
Core for
26 roles

The problem

Build Pascal's triangle one row at a time and return its first n rows. Every row starts and ends with 1, and each value in between is the total of the two values sitting just above it in the previous row.

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-29

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.

More Arrays problems

Track in your role's order

Pick your target role and all 370 problems resequence to what that interview actually asks.

Start free

Problem set and role mapping as of .