Count the number of ways to fill K boxes with N distinct items


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: 120

Input: N = 5, k = 3
Output: 1500



Approach: We will use the inclusion-exclusion principle to count the ways.

  1. 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.
  2. 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.
  3. 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…
  4. Hence, the total number of ways:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 numbers
int factorial[100005];
  
// Function to calculate factorial 
// of all numbers
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) time
int 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 x
int 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 code
signed main()
{
    int N = 5;
    int K = 5;
      
    cout << CountWays(N, K) << "\n";
      
    return 0;
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to calculate the 
# above formula
  
mod = 1000000007
  
# To store the factorials 
# of all numbers
factorial = [0 for i in range(100005)]
  
# Function to calculate factorial 
# of all numbers
def 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) time
def 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 x
def 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 code
if __name__ == '__main__':
      
    N = 5
    K = 5
      
    print(CountWays(N, K))
  
# This code is contributed by Surendra_Gangwar

chevron_right


Output:

120

Time complexity: O(N*log N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : SURENDRA_GANGWAR