Binomial CoefficientProblem

Pattern: DP recipe: recursion to tabulation

medium

C(n, r) counts the ways to choose r items from n. Either the last item is chosen (choose r - 1 from the other n - 1) or not (choose r from n - 1), so C(n, r) = C(n-1, r-1) + C(n-1, r): Pascal's triangle, built one row at a time.

No verified practice link yet. The guide below states the problem in full, so you can still solve it here.

The problem

Return C(n, r), the number of ways to choose r items from n, modulo 10⁹ + 7; it is 0 when r > n. The catalogue has no practice link for this one.

Think first

  • What happens to the last item in any choice?
  • What smaller problems does that give?
  • Why not use factorials directly?

Hints

    Brute force, and why it fails

    Compute n! / (r! (n - r)!) with big integers: fine in Python, overflows elsewhere.

    The key insight

    Pascal's rule uses only additions, so every step stays small under the modulo.

    Dry run

    row1 2 1

    n = 3, r = 2. Row 0: [1]. Row 1: [1, 1]. Row 2: [1, 2, 1].

    Step 1 of 3

    The plan

    row = [1, 0, ...]
    for i in 1..n: for j from min(i, r) down to 1: row[j] += row[j - 1]
    return row[r]
    

    Complexity

    Time
    O(n × r)
    Space
    O(r)

    One row of the triangle, updated from right to left.

    Edge cases

    • r = 0: 1.
    • r > n: 0.
    • r = n: 1.
    I've built my logic, show the code

    Java

    class Solution {
        public int nCr(int n, int r) {
            final int MOD = 1_000_000_007;
            if (r > n) return 0;
            int[] row = new int[r + 1];             // one row of Pascal's triangle, updated in place
            row[0] = 1;
            for (int i = 1; i <= n; i++)
                for (int j = Math.min(i, r); j > 0; j--) row[j] = (row[j] + row[j - 1]) % MOD;   // C(i, j) = C(i-1, j) + C(i-1, j-1)
            return row[r];
        }
    }

    C++

    class Solution {
    public:
        int nCr(int n, int r) {
            const int MOD = 1000000007;
            if (r > n) return 0;
            vector<int> row(r + 1, 0);              // one row of Pascal's triangle, updated in place
            row[0] = 1;
            for (int i = 1; i <= n; i++)
                for (int j = min(i, r); j > 0; j--) row[j] = (row[j] + row[j - 1]) % MOD;   // C(i, j) = C(i-1, j) + C(i-1, j-1)
            return row[r];
        }
    };

    Python

    class Solution:
        def nCr(self, n: int, r: int) -> int:
            MOD = 1_000_000_007
            if r > n:
                return 0
            row = [1] + [0] * r                     # one row of Pascal's triangle, updated in place
            for i in range(1, n + 1):
                for j in range(min(i, r), 0, -1):
                    row[j] = (row[j] + row[j - 1]) % MOD   # C(i, j) = C(i-1, j) + C(i-1, j-1)
            return row[r]

    Common mistakes

    • Updating the row left to right, which reuses new values.
    • Forgetting the modulo.

    Similar problems