Given two integer N and R, the task is to calculate the number of ways to distribute N identical objects into R distinct groups such that no groups are left empty.
Input: N = 4, R = 2
No of objects in 1st group = 1, in second group = 3
No of objects in 1st group = 2, in second group = 2
No of objects in 1st group = 3, in second group = 1
Input: N = 5, R = 3
Approach: Idea is to use Multinomial theorem. Let us suppose that x1 objects are placed in the first group, x2 objects are placed in second group and xR objects are placed in the Rth group. It is given that,
x1 + x2 + x3 +…+ xR = N for all xi ≥ 1 for 1 ≤ i ≤ R
Now replace every xi with yi + 1 for all 1 ≤ i ≤ R. Now all the y variaables are greater than or equal to zero.
The equation becomes,
y1 + y2 + y3 + … + yR + R = N for all yi ≥ 0 for 1 ≤ i ≤ R
y1 + y2 + y3 + … + yR = N – R
It now reduces to that standard multinomial equation whose solution is (N – R) + R – 1CR – 1.
The solution of this equation is given by N – 1CR – 1.
Below is the implementation of the above approach:
Time Complexity: O(R)
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.