Given ‘a’ balls of type ‘A’, ‘b’ balls of type ‘B’ and ‘c’ balls of type ‘C’. You need to find the total number of ways to arrange the balls in a straight line such that adjacent balls are of different types.
In other words, find the total ways to arrange the given balls in such a way that no two balls of the same type are adjacent.
For Example :Suppose we have 2 balls of type ‘A’, 1 ball of type ‘B’ and 1 ball of type ‘C’, following are the ways to arrange them in the required fashion.
ABCA
ABAC
ACBA
ACAB
BACA
CABA
Hence, there is a total of six ways.
The first line of input contains an integer ‘T’ denoting the number of test cases.
The first line of each test contains three space-separated positive integers a, b, c, denoting the number of balls of type ‘A’, ‘B’, and ‘C’ respectively.
Output Format :
For each test case, print the total ways to arrange the balls such that adjacent balls are of a different type in a single line.
Print the output of each test case in a separate line.
Note :
You don’t have to print anything, it has already been taken care of. Just complete the function.
If there is no way, return 0.
1 <= T <= 100
0 <= a, b, c <= 15
Time limit: 1 sec
2
1 2 1
1 1 1
6
6
Test Case 1: We have one ball of type A, two balls of type B and one ball of type C. All the possible arrangements such that no two adjacent balls are of the same type are shown below.
ABCB
BACB
BABC
BCAB
BCBA
CBAB
These are all the six possible arrangements.
Test Case 2: We have 1 ball of each type. All the possible arrangements are -
ABC
ACB
BAC
BCA
CAB
CBA
These are all six possible arrangements.
2
4 5 3
8 3 1
588
0
Can you do this recursively?
This problem can be solved by solving its subproblems and then combining the solutions of the solved subproblems to solve the original problem. We will do this using recursion. We will keep track of the next ball we want to add in the line. Initially, we have three options, to begin with. We can start by adding A or B or C. After that, at each step, we have two options. We can find the number of ways to make the required arrangements from the remaining balls.
Algorithm:
O(2^(min(a,b,c)), where ‘a’, ‘b’, ‘c’ are the number of balls of type ‘A’, ‘B’, and ‘C’ respectively.
As we are making three calls to the helper function whose time complexity is O(2^(min(a, b, c)).
O(min(a, b, c)), where a, b, c denoting the number of balls of type ‘A’, ‘B’, and ‘C’ respectively.
This is the recursion stack space used by the algorithm.