Ecommet

Pascal’s Triangle

Easy Problem 28 of 151 Java and Python

Problem

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

Each row starts and ends with 1, and every other number is the sum of the two numbers directly above it.

Example 1

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

Example 2

Input
numRows = 1
Output
[[1]]

Constraints

  • 1 ≤ numRows ≤ 30

Explanation

Row r has r + 1 numbers. Its inside entries come straight from the previous row: row[c] = prev[c - 1] + prev[c].

Each value is also the binomial coefficient C(r, c), which can be computed on its own, but building rows from the previous one is simpler and avoids overflow.

Approach 1 · Naive

Compute each entry as nCr

  • Time O(n³)
  • Space O(1) besides the output

Entry c of row r is C(r, c) = r! / (c! (r – c)!). Compute it with a running product for each entry independently.

  1. For each row r and column c, compute C(r, c) with a loop.
  2. Collect the rows.
Java
import java.util.*;

class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> rows = new ArrayList<>();
        for (int r = 0; r < numRows; r++) {
            List<Integer> row = new ArrayList<>();
            for (int c = 0; c <= r; c++) {
                row.add((int) choose(r, c));
            }
            rows.add(row);
        }
        return rows;
    }

    private long choose(int n, int k) {
        long result = 1;
        for (int i = 1; i <= k; i++) {
            result = result * (n - k + i) / i;
        }
        return result;
    }
}
Python
class Solution:
    def generate(self, numRows: int) -> List[List[int]]:
        def choose(n, k):
            result = 1
            for i in range(1, k + 1):
                result = result * (n - k + i) // i
            return result

        return [[choose(r, c) for c in range(r + 1)] for r in range(numRows)]

Approach 2 · Optimal

Build each row from the one above

  • Time O(n²)
  • Space O(1) besides the output

Start every row with 1s, then fill the inside from the previous row.

  1. Row 0 is [1].
  2. For row r, make r + 1 ones and set row[c] = prev[c - 1] + prev[c] for 0 < c < r.
Java
import java.util.*;

class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> rows = new ArrayList<>();
        for (int r = 0; r < numRows; r++) {
            List<Integer> row = new ArrayList<>();
            for (int c = 0; c <= r; c++) {
                if (c == 0 || c == r) {
                    row.add(1);
                } else {
                    List<Integer> prev = rows.get(r - 1);
                    row.add(prev.get(c - 1) + prev.get(c));
                }
            }
            rows.add(row);
        }
        return rows;
    }
}
Python
class Solution:
    def generate(self, numRows: int) -> List[List[int]]:
        rows = [[1]]
        for r in range(1, numRows):
            prev = rows[-1]
            row = [1] * (r + 1)
            for c in range(1, r):
                row[c] = prev[c - 1] + prev[c]
            rows.append(row)
        return rows

Complexity compared

ApproachTimeSpace
Naive Compute each entry as nCrO(n³)O(1) besides the output
Optimal Build each row from the one aboveO(n²)O(1) besides the output

Key takeaways

  • Common follow-ups: return only row r (keep one row and update it right to left), or a single value C(r, c).

Your notes

Saved in this browser as you type.

Solved it on your own?

Mark it done to track your progress, or star it to come back before an interview.

Next problem