We are given N items which are of total K different colors. Items of the same color are indistinguishable and colors can be numbered from 1 to K and count of items of each color is also given as k1, k2, and so on. Now we need to arrange these items one by one under the constraint that the last item of color i comes before the last item of color (i + 1) for all possible colors. Our goal is to find out how many ways this can be achieved.
Examples:Â
Input : N = 3 k1 = 1 k2 = 2 Output : 2 Explanation : Possible ways to arrange are, k1, k2, k2 k2, k1, k2 Input : N = 4 k1 = 2 k2 = 2 Output : 3 Explanation : Possible ways to arrange are, k1, k2, k1, k2 k1, k1, k2, k2 k2, k1, k1, k2
Method 1:Â
We can solve this problem using dynamic programming. Let dp[i] stores the number of ways to arrange first i colored items. For one colored item answer will be one because there is only one way. Now Let’s assume all items are in a sequence. Now, to go from dp[i] to dp[i + 1], we need to put at least one item of color (i + 1) at the very end, but the other items of color (i + 1) can go anywhere in the sequence. The number of ways to arrange the item of color (i + 1) is combination of (k1 + k2 .. + ki + k(i + 1) – 1) over (k(i + 1) – 1) which can be represented as (k1 + k2 .. + ki + k(i + 1) – 1)C(k(i + 1) – 1). In this expression we subtracted one because we need to put one item at the very end.Â
In the below code, first, we have calculated the combination values, you can read more about that from here. After that we looped over all the different colors and calculated the final value using the above relation.
C++
// C++ program to find number of ways to arrange // items under given constraint #include <bits/stdc++.h> using namespace std; Â
// method returns number of ways with which items // can be arranged int waysToArrange( int N, int K, int k[]) { Â Â Â Â int C[N + 1][N + 1]; Â Â Â Â int i, j; Â
    // Calculate value of Binomial Coefficient in     // bottom up manner     for (i = 0; i <= N; i++) {         for (j = 0; j <= i; j++) { Â
            // Base Cases             if (j == 0 || j == i)                 C[i][j] = 1; Â
            // Calculate value using previously             // stored values             else                 C[i][j] = (C[i - 1][j - 1] + C[i - 1][j]);         }     } Â
    // declare dp array to store result up to ith     // colored item     int dp[K]; Â
    // variable to keep track of count of items     // considered till now     int count = 0; Â
    dp[0] = 1; Â
    // loop over all different colors     for ( int i = 0; i < K; i++) { Â
        // populate next value using current value         // and stated relation         dp[i + 1] = (dp[i] * C[count + k[i] - 1][k[i] - 1]);         count += k[i];     } Â
    // return value stored at last index     return dp[K]; } Â
// Driver code to test above methods int main() { Â Â Â Â int N = 4; Â Â Â Â int k[] = { 2, 2 }; Â
    int K = sizeof (k) / sizeof ( int );     cout << waysToArrange(N, K, k) << endl;     return 0; } |
Java
// Java program to find number of ways to arrange // items under given constraint import java.io.*; class GFG { Â
    // method returns number of ways with which items     // can be arranged     static int waysToArrange( int N, int K, int [] k)     {         int [][] C = new int [N + 1 ][N + 1 ];         int i, j; Â
        // Calculate value of Binomial Coefficient in         // bottom up manner         for (i = 0 ; i <= N; i++) {             for (j = 0 ; j <= i; j++) { Â
                // Base Cases                 if (j == 0 || j == i) {                     C[i][j] = 1 ;                 } Â
                // Calculate value using previously                 // stored values                 else {                     C[i][j]                         = (C[i - 1 ][j - 1 ] + C[i - 1 ][j]);                 }             }         } Â
        // declare dp array to store result up to ith         // colored item         int [] dp = new int [K + 1 ]; Â
        // variable to keep track of count of items         // considered till now         int count = 0 ; Â
        dp[ 0 ] = 1 ; Â
        // loop over all different colors         for (i = 0 ; i < K; i++) { Â
            // populate next value using current value             // and stated relation             dp[i + 1 ]                 = (dp[i] * C[count + k[i] - 1 ][k[i] - 1 ]);             count += k[i];         } Â
        // return value stored at last index         return dp[K];     } Â
    // Driver code     public static void main(String[] args)     {         int N = 4 ;         int [] k = new int [] { 2 , 2 };         int K = k.length;         System.out.println(waysToArrange(N, K, k));     } } Â
// This code has been contributed by 29AjayKumar |
Python3
# Python3 program to find number of ways # to arrange items under given constraint import numpy as np Â
# method returns number of ways with # which items can be arranged def waysToArrange(N, K, k) : Â
    C = np.zeros((N + 1 , N + 1 )) Â
    # Calculate value of Binomial     # Coefficient in bottom up manner     for i in range (N + 1 ) :         for j in range (i + 1 ) : Â
            # Base Cases             if (j = = 0 or j = = i) :                 C[i][j] = 1 Â
            # Calculate value using previously             # stored values             else :                 C[i][j] = (C[i - 1 ][j - 1 ] +                            C[i - 1 ][j]) Â
    # declare dp array to store result     # up to ith colored item     dp = np.zeros((K + 1 )) Â
    # variable to keep track of count     # of items considered till now     count = 0 Â
    dp[ 0 ] = 1 Â
    # loop over all different colors     for i in range (K) : Â
        # populate next value using current         # value and stated relation         dp[i + 1 ] = (dp[i] * C[count + k[i] - 1 ][k[i] - 1 ])         count + = k[i]          # return value stored at last index     return dp[K] Â
# Driver code if __name__ = = "__main__" : Â
    N = 4     k = [ 2 , 2 ] Â
    K = len (k)     print ( int (waysToArrange(N, K, k))) Â
# This code is contributed by Ryuga |
C#
// C# program to find number of ways to arrange // items under given constraint using System; Â
class GFG {     // method returns number of ways with which items     // can be arranged     static int waysToArrange( int N, int K, int [] k)     {         int [,] C = new int [N + 1, N + 1];         int i, j;              // Calculate value of Binomial Coefficient in         // bottom up manner         for (i = 0; i <= N; i++)         {             for (j = 0; j <= i; j++)             {                      // Base Cases                 if (j == 0 || j == i)                     C[i, j] = 1;                      // Calculate value using previously                 // stored values                 else                     C[i, j] = (C[i - 1, j - 1] + C[i - 1, j]);             }         }              // declare dp array to store result up to ith         // colored item         int [] dp = new int [K + 1];              // variable to keep track of count of items         // considered till now         int count = 0;              dp[0] = 1;              // loop over all different colors         for (i = 0; i < K; i++) {                  // populate next value using current value             // and stated relation             dp[i + 1] = (dp[i] * C[count + k[i] - 1, k[i] - 1]);             count += k[i];         }              // return value stored at last index         return dp[K];     }          // Driver code     static void Main()     {         int N = 4;         int [] k = new int []{ 2, 2 };         int K = k.Length;         Console.Write(waysToArrange(N, K, k));     } } Â
// This code is contributed by DrRoot_ |
PHP
<?php // PHP program to find number of // ways to arrange items under // given constraint Â
// method returns number of ways // with which items can be arranged function waysToArrange( $N , $K , $k ) {     $C [ $N + 1][ $N + 1] = array ( array ());          // Calculate value of Binomial     // Coefficient in bottom up manner     for ( $i = 0; $i <= $N ; $i ++)     {         for ( $j = 0; $j <= $i ; $j ++)         { Â
            // Base Cases             if ( $j == 0 || $j == $i )                 $C [ $i ][ $j ] = 1; Â
            // Calculate value using             // previously stored values             else                 $C [ $i ][ $j ] = ( $C [ $i - 1][ $j - 1] +                               $C [ $i - 1][ $j ]);         }     } Â
    // declare dp array to store     // result up to ith colored item     $dp [ $K ] = array (); Â
    // variable to keep track of count     // of items considered till now     $count = 0; Â
    $dp [0] = 1; Â
    // loop over all different colors     for ( $i = 0; $i < $K ; $i ++)     { Â
        // populate next value using         // current value and stated relation         $dp [ $i + 1] = ( $dp [ $i ] * $C [ $count +                         $k [ $i ] - 1][ $k [ $i ] - 1]);         $count += $k [ $i ];     } Â
    // return value stored at     // last index     return $dp [ $K ]; } Â
// Driver code $N = 4; $k = array ( 2, 2 ); Â
$K = sizeof( $k ); echo waysToArrange( $N , $K , $k ), "\n" ; Â
// This code is contributed by jit_t ?> |
Javascript
<script> // Javascript program to find number of ways to arrange // items under given constraint. Â
    // method returns number of ways with which items     // can be arranged     function waysToArrange(N, K, k)     {         let C = new Array(N + 1);         // Loop to create 2D array using 1D array         for (let i = 0; i < C.length; i++) {             C[i] = new Array(2);         }                  let i, j;            // Calculate value of Binomial Coefficient in         // bottom up manner         for (i = 0; i <= N; i++)         {             for (j = 0; j <= i; j++)             {                    // Base Cases                 if (j == 0 || j == i)                 {                     C[i][j] = 1;                 }                                    // Calculate value using previously                 // stored values                 else                 {                     C[i][j] = (C[i - 1][j - 1] + C[i - 1][j]);                 }             }         }            // declare dp array to store result up to ith         // colored item         let dp = Array.from({length: K+1}, (_, i) => 0);            // variable to keep track of count of items         // considered till now         let count = 0;            dp[0] = 1;            // loop over all different colors         for (i = 0; i < K; i++)         {                // populate next value using current value             // and stated relation             dp[i + 1] = (dp[i] * C[count + k[i] - 1][k[i] - 1]);             count += k[i];         }            // return value stored at last index         return dp[K];     }    // driver function Â
        let N = 4;         let k = [2, 2];         let K = k.length;         document.write(waysToArrange(N, K, k));    </script>   |
3
Time Complexity: O(N2)
Auxiliary space: O(N*N)
This article is contributed by Utkarsh Trivedi. If you like neveropen and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the neveropen main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!