Permutation CoefficientProblem

Pattern: DP recipe: recursion to tabulation

medium

P(n, k) counts ordered arrangements of k items out of n: n choices for the first, n - 1 for the second, and so on. Multiply the k factors, taking the remainder after each step.

The problem

Return P(n, k) = n × (n - 1) × … × (n - k + 1), modulo 10⁹ + 7; 0 when k > n.

Think first

  • How many choices for the first position?
  • And for the second?
  • How many factors?

Hints

    Brute force, and why it fails

    Compute n! / (n - k)!: big numbers, or a modular inverse.

    The key insight

    The product of k falling factors is P(n, k) directly; the DP view is P(n, k) = P(n-1, k-1) × n.

    Dry run

    p10

    n = 10, k = 2. The first place has 10 choices.

    Step 1 of 2

    The plan

    p = 1; for i in 0..k-1: p = p × (n - i) mod M
    

    Complexity

    Time
    O(k)
    Space
    O(1)

    k multiplications.

    Edge cases

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

    Java

    class Solution {
        public int nPr(int n, int k) {
            final long MOD = 1_000_000_007L;
            if (k > n) return 0;
            long p = 1;
            for (int i = 0; i < k; i++) p = p * (n - i) % MOD;   // P(n, k) = n × (n - 1) × ... × (n - k + 1)
            return (int) p;
        }
    }

    C++

    class Solution {
    public:
        int nPr(int n, int k) {
            const long long MOD = 1000000007LL;
            if (k > n) return 0;
            long long p = 1;
            for (int i = 0; i < k; i++) p = p * (n - i) % MOD;   // P(n, k) = n × (n - 1) × ... × (n - k + 1)
            return static_cast<int>(p);
        }
    };

    Python

    class Solution:
        def nPr(self, n: int, k: int) -> int:
            MOD = 1_000_000_007
            if k > n:
                return 0
            p = 1
            for i in range(k):
                p = p * (n - i) % MOD               # P(n, k) = n × (n - 1) × ... × (n - k + 1)
            return p

    Common mistakes

    • Overflow before the modulo.
    • Multiplying k + 1 factors.

    Similar problems