Given two values N and K. Find the number of ways to arrange the N distinct items in the boxes such that exactly K (K<N) boxes are used from the N distinct boxes. The answer can be very large so return the answer modulo 109 + 7.
Note: 1 <= N <= K <= 105.Â
Prerequisites: Factorial of a number, Compute nCr % p
Examples:Â
Input: N = 5, k = 5Â
Output: 120Input: N = 5, k = 3Â
Output: 1500Â
Approach: We will use the inclusion-exclusion principle to count the ways.Â
- Let us assume that the boxes are numbered 1 to N and now we have to choose any K boxes and use them. The number of ways to do this is NCK.
- Now any item can be put in any of the chosen boxes, hence the number of ways to arrange them is KN But here, we may count arrangements with some boxes empty. Hence, we will use the inclusion-exclusion principle to ensure that we count ways with all K boxes filled with at least one item.
- Let us understand the application of the inclusion-exclusion principle:Â
- So out of KN ways, we subtract the case when at least 1 box(out of K) is empty. Hence, subtractÂ
(KC1)*((K-1)N). - Note that here, The cases where exactly two boxes are empty are subtracted twice(once when we choose the first element in (KC1) ways, and then when we choose the second element in (KC1) ways).
- Hence, we add these ways one time to compensate. So we add (KC2)*((K – 2)N).
- Similarly, here we need to add the number of ways when at least 3 boxes were empty, and so on…
- So out of KN ways, we subtract the case when at least 1 box(out of K) is empty. Hence, subtractÂ
- Hence, the total number of ways:
Â
C++
// C++ program to calculate the // above formula#include <bits/stdc++.h>#define mod 1000000007#define int long longÂ
using namespace std;Â
// To store the factorials // of all numbersint factorial[100005];Â
// Function to calculate factorial // of all numbersvoid StoreFactorials(int n){Â Â Â Â factorial[0] = 1;Â Â Â Â for (int i = 1; i <= n; i++)Â Â Â Â {Â Â Â Â Â Â Â Â factorial[i] = Â Â Â Â Â Â Â Â Â Â (i * factorial[i - 1])Â Â Â Â Â Â Â Â Â Â Â Â % mod;Â Â Â Â Â Â Â Â Â Â Â Â Â }}Â
// Calculate x to the power y // in O(log n) timeint Power(int x, int y){Â Â Â Â int ans = 1;Â Â Â Â while (y > 0) {Â Â Â Â Â Â Â Â if (y % 2 == 1) {Â Â Â Â Â Â Â Â Â Â Â Â ans = (ans * x) % mod;Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â x = (x * x) % mod;Â Â Â Â Â Â Â Â y /= 2;Â Â Â Â }Â Â Â Â return ans;}Â
// Function to find inverse mod of // a number xint invmod(int x){Â Â Â Â return Power(x, mod - 2);}Â
// Calculate (n C r)int nCr(int n, int r){Â Â Â Â return (factorial[n] Â Â Â Â Â Â Â Â Â Â Â Â * invmod((factorial[r]Â Â Â Â Â Â Â Â Â Â Â Â * factorial[n - r]) % mod))Â Â Â Â Â Â Â Â Â Â Â Â % mod;}Â
int CountWays(int n,int k){Â Â Â Â StoreFactorials(n);Â
         // Loop to compute the formula     // evaluated    int ans = 0;    for (int i = k; i >= 0; i--)    {        if (i % 2 == k % 2)         {            // Add even power terms            ans = (ans + (Power(i, n)                  * nCr(k, i)) % mod)                   % mod;        }        else        {            // Subtract odd power terms            ans = (ans + mod - (Power(i, n)                   * nCr(k, i)) % mod) % mod;        }    }         // Choose the k boxes which     // were used    ans = (ans * nCr(n, k)) % mod;Â
    return ans;}Â
// Driver codesigned main(){Â Â Â Â int N = 5;Â Â Â Â int K = 5;Â Â Â Â Â Â Â Â Â cout << CountWays(N, K) << "\n";Â Â Â Â Â Â Â Â Â return 0;} |
Java
// Java program to calculate the // above formula    import java.util.*; Â
class GFG{Â Â Â Â Â Â Â Â Â Â Â Â Â static long mod = 1000000007;Â
// To store the factorials // of all numbersstatic long factorial[] = new long[100005];Â
// Function to calculate factorial // of all numbersstatic void StoreFactorials(int n){Â Â Â Â factorial[0] = 1;Â Â Â Â Â Â Â Â Â for(int i = 1; i <= n; i++)Â Â Â Â {Â Â Â Â Â Â Â Â factorial[i] = (i * Â Â Â Â Â Â Â Â factorial[i - 1]) % mod;Â Â Â Â }}Â
// Calculate x to the power y // in O(log n) timestatic long Power(long x, long y){Â Â Â Â long ans = 1;Â Â Â Â Â Â Â Â Â while (y > 0) Â Â Â Â {Â Â Â Â Â Â Â Â if (y % 2 == 1) Â Â Â Â Â Â Â Â {Â Â Â Â Â Â Â Â Â Â Â Â ans = (ans * x) % mod;Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â x = (x * x) % mod;Â Â Â Â Â Â Â Â y /= 2;Â Â Â Â }Â Â Â Â return ans;}Â
// Function to find inverse mod of // a number xstatic long invmod(long x){Â Â Â Â return Power(x, mod - 2);}Â
// Calculate (n C r)static long nCr(int n, int r){Â Â Â Â return (factorial[n] * Â Â Â Â invmod((factorial[r] *Â Â Â Â Â Â Â Â Â Â Â Â factorial[n - r]) % mod)) % mod;}Â
static long CountWays(int n,int k){Â Â Â Â StoreFactorials(n);Â
    // Loop to compute the formula     // evaluated    long ans = 0;    for(int i = k; i >= 0; i--)    {        if (i % 2 == k % 2)         {                         // Add even power terms            ans = (ans + (Power(i, n) *                    nCr(k, i)) % mod) % mod;        }        else        {                         // Subtract odd power terms            ans = (ans + mod - (Power(i, n) *                   nCr(k, i)) % mod) % mod;        }    }         // Choose the k boxes which     // were used    ans = (ans * nCr(n, k)) % mod;Â
    return ans;}             // Driver Code        public static void main (String[] args){            int N = 5;    int K = 5;         System.out.print(CountWays(N, K) + "\n");}        }Â
// This code is contributed by math_lover |
Python3
# Python3 program to calculate the # above formulaÂ
mod = 1000000007Â
# To store the factorials # of all numbersfactorial = [0 for i in range(100005)]Â
# Function to calculate factorial # of all numbersdef StoreFactorials(n):Â Â Â Â Â Â Â Â Â factorial[0] = 1Â Â Â Â for i in range(1, n + 1, 1):Â Â Â Â Â Â Â Â factorial[i] = (i * factorial[i - 1]) % modÂ
# Calculate x to the power y # in O(log n) timedef Power(x, y):         ans = 1    while (y > 0):                 if (y % 2 == 1):            ans = (ans * x) % mod                     x = (x * x) % mod        y //= 2             return ansÂ
# Function to find inverse mod # of a number xdef invmod(x):Â Â Â Â Â Â Â Â Â return Power(x, mod - 2)Â
# Calculate (n C r)def nCr(n, r):Â Â Â Â return ((factorial[n] * invmod((factorial[r] *Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â factorial[n - r]) %Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â mod)) % mod)Â
def CountWays(n, k):         StoreFactorials(n)         # Loop to compute the formula     # evaluated    ans = 0    i = k         while(i >= 0):        if (i % 2 == k % 2):                         # Add even power terms            ans = ((ans + (Power(i, n) *                           nCr(k, i)) % mod) % mod)        else:                         # Subtract odd power terms            ans = ((ans + mod - (Power(i, n) *                                 nCr(k, i)) %                                 mod) % mod)        i -= 1             # Choose the k boxes which     # were used    ans = (ans * nCr(n, k)) % mod         return ansÂ
# Driver codeif __name__ == '__main__':Â Â Â Â Â Â Â Â Â N = 5Â Â Â Â K = 5Â Â Â Â Â Â Â Â Â print(CountWays(N, K))Â
# This code is contributed by Surendra_Gangwar |
C#
// C# program to calculate the // above formula    using System; using System.Collections;using System.Collections.Generic; Â
class GFG{Â Â Â Â Â Â Â Â Â Â Â Â Â static long mod = 1000000007;Â
// To store the factorials // of all numbersstatic long []factorial = new long[100005];Â
// Function to calculate factorial // of all numbersstatic void StoreFactorials(int n){Â Â Â Â factorial[0] = 1;Â Â Â Â Â Â Â Â Â for(int i = 1; i <= n; i++)Â Â Â Â {Â Â Â Â Â Â Â Â factorial[i] = (i * Â Â Â Â Â Â Â Â factorial[i - 1]) % mod;Â Â Â Â }}Â
// Calculate x to the power y // in O(log n) timestatic long Power(long x, long y){Â Â Â Â long ans = 1;Â Â Â Â Â Â Â Â Â while (y > 0) Â Â Â Â {Â Â Â Â Â Â Â Â if (y % 2 == 1) Â Â Â Â Â Â Â Â {Â Â Â Â Â Â Â Â Â Â Â Â ans = (ans * x) % mod;Â Â Â Â Â Â Â Â }Â Â Â Â Â Â Â Â x = (x * x) % mod;Â Â Â Â Â Â Â Â y /= 2;Â Â Â Â }Â Â Â Â return ans;}Â
// Function to find inverse mod of // a number xstatic long invmod(long x){Â Â Â Â return Power(x, mod - 2);}Â
// Calculate (n C r)static long nCr(int n, int r){Â Â Â Â return (factorial[n] * Â Â Â Â invmod((factorial[r] *Â Â Â Â Â Â Â Â Â Â Â Â factorial[n - r]) % mod)) % mod;}Â
static long CountWays(int n,int k){Â Â Â Â StoreFactorials(n);Â
    // Loop to compute the formula     // evaluated    long ans = 0;    for(int i = k; i >= 0; i--)    {        if (i % 2 == k % 2)         {                         // Add even power terms            ans = (ans + (Power(i, n) *                   nCr(k, i)) % mod) % mod;        }        else        {                         // Subtract odd power terms            ans = (ans + mod - (Power(i, n) *                  nCr(k, i)) % mod) % mod;        }    }         // Choose the k boxes which     // were used    ans = (ans * nCr(n, k)) % mod;Â
    return ans;}             // Driver Code        public static void Main (string[] args){            int N = 5;    int K = 5;         Console.Write(CountWays(N, K) + "\n");}        }Â
// This code is contributed by rutvik_56 |
Javascript
<script>Â Â Â Â
    let mod = 1000000007;    let factorial = []Â
    function StoreFactorials(n){        factorial[0] = 1;                 for(let i = 1; i <= n; i++){            factorial[i] = (i *            factorial[i - 1]) % mod;        }    }         // Calculate x to the power y in O(log n) time    function Power(x, y){        var ans = 1;                 while(y > 0){            if(y % 2 == 1){                ans = (ans * x) % mod;            }            x = (x * x) % mod;            y /= 2;        }        return ans;    }Â
    // Function to find inverse mod of a number x    function invmod(x){        return Power(x, mod-2);    }         // Calculate (nCr)    function nCr(n, r){        return (factorial[n] *            invmod((factorial[r] *            factorial[n - r]) % mod)) % mod;    }Â
    function CountWays(n, k){         StoreFactorials(n);                 // Loop to compute the formula evaluated        var ans = 0;        for(let i = k; i >= 0; i--)        {            if (i % 2 == k % 2)            {                                  // Add even power terms                ans = (ans + (Power(i, n) *                       nCr(k, i)) % mod) % mod;            }            else            {                                  // Subtract odd power terms                ans = (ans + mod - (Power(i, n) *                       nCr(k, i)) % mod) % mod;            }        }                  // Choose the k boxes which        // were used        ans = (ans * nCr(n, k)) % mod;              return ans;    }Â
    var N = 5;    var K = 5;         document.write(CountWays(N, K));         // This code is contributed by lokeshmvs21.</script> |
120
Â
Time complexity: O(N*log N)
Auxiliary Space: O(105)
Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

