Given three integers N, X and Y. The task is to find the number of ways to arrange 2*N persons along two sides of a table with N number of chairs on each side such that X persons are on one side and Y persons are on the opposite side. Note: Both X and Y are less than or equals to N. Examples:
Input : N = 5, X = 4, Y = 2 Output : 57600 Explanation : The total number of person 10. X men on one side and Y on other side, then 10 – 4 – 2 = 4 persons are left. We can choose 5 – 4 = 1 of them on one side in ways and the remaining persons will automatically sit on the other side. On each side arrangement is done in 5! ways. The number of ways is .5!5!
Input : N = 3, X = 1, Y = 2 Output : 108
Approach : The total number of person 2*N. Let call both the sides as A and B. X men on side A and Y on side B, then 2*N – X – Y persons are left. We can choose N-X of them for side A in ways and the remaining persons will automatically sit on the other side B. On each side arrangement is done in N! ways. The number of ways to arrange 2*N persons along two sides of a table is .N!N! Below is the implementation of the above approach :
returnnCr(2 * n - x - y, n - x) * factorial(n) * factorial(n);
}
// Driver code
varn = 5, x = 4, y = 2;
// Function call
document.write(NumberOfWays(n, x, y));
// This code contributed by Rajput-Ji
</script>
Output:
57600
Time Complexity: O(N) Auxiliary Space: O(N), for recursive stack space.
Method – 2 O(1) Space Solution
In the above solution, we implemented the factorial function in a recursive manner if we implement the factorial function in an iterative manner then we don’t need O(n) auxiliary extra stack space so this way solution becomes O(1) space complexity solution Below is an implementation for the same :
C++
// C++ code for above mentioned solution
#include <bits/stdc++.h>
usingnamespacestd;
// Iterative function to find factorial of a number
// Function to find the number of ways to arrange 2*N persons
functionnumberOfWays(n, x, y) {
returnnCr(2 * n - x - y, n - x) * factorial(n) * factorial(n);
}
// Driver code
const n = 5, x = 4, y = 2;
// Function call
console.log(numberOfWays(n, x, y));
// This code is contributed by Sundaram
Output
57600
Time Complexity: O(N) Auxiliary Space: O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!