Ways to arrange Balls such that adjacent balls are of different types
There are ‘p’ balls of type P, ‘q’ balls of type Q and ‘r’ balls of type R. Using the balls we want to create a straight line such that no two balls of same type are adjacent.
Input : p = 1, q = 1, r = 0 Output : 2 There are only two arrangements PQ and QP Input : p = 1, q = 1, r = 1 Output : 6 There are only six arrangements PQR, QPR, QRP, RQP, PRQ and RPQ Input : p = 2, q = 1, r = 1 Output : 6 There are only six arrangements PQRP, QPRP, PRQP, RPQP, PRPQ and PQPR
We strongly recommend that you click here and practice it, before moving on to the solution.
The naive solution to this problem is a recursive solution. We recursively call for three cases
1) Last ball to be placed is of type P
2) Last ball to be placed is of type Q
3) Last ball to be placed is of type R
Below is the implementation of above idea.
Time Complexity: The time complexity of this program is O(3^n), where n is the total number of balls. This is because for each ball placement, there are three possibilities (p, q, or r) and there are n balls in total. Therefore, the total number of possible arrangements is 3^n.
Space Comlexity: The space complexity of this program is O(1) because there are no additional data structures being used beyond the input variables and the return value. The program uses recursive function calls to calculate the number of ways to arrange the balls, and these function calls use the call stack to store intermediate values. However, the depth of the call stack is at most n, so the space complexity is O(1) in terms of the input size.
We can observe that there are many subproblems being solved again and again so the problem can be solved using Dynamic Programming (DP). We can easily make memoization solution to this problem.
Time complexity : O(p*q*r)
Auxiliary Space : O(p*q*r*3)
This article is contributed by Bhavuk Chawla. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to email@example.com. See your article appearing on the GeeksforGeeks 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.
Please Login to comment...