Count of ways N elements can form two different sets containing N/2 elements each
Given a number N, representing count of elements and is equal to 2K, the task is to find the number of ways these elements can be form 2 sets containing K elements each.
Input: N = 4
Explanation: The 3 sets consisting of 2 (= N/2) elements are:
[1, 2], [3, 4]
[1, 3], [2, 4]
[1, 4], [2, 3]
Input: N = 20
Approach: It is to be observed that the concept of combinations has to apply in order to choose the elements for each set.
It is known that the number of ways to choose r things from a total of n things is given by:
nCr = n!/(n-r)!*r!
Now, the above formula can be modified to solve the given problem:
- Here, N/2 elements have to be chosen from N elements to form each set. Hence, r = N/2.
- It is to be noted that the same element cannot be simultaneously present in the two sets. So, the formula of nCr has to be divided by 2.
- Also, the element present in each set can arrange themselves in (N/2-1)! ways. Since there are two sets, the formula will be multiplied by this factor twice.
The modified formula obtained is given by:
Number of ways = ((N! / (N – r)!*r!) / 2) * (N / 2 – 1)!*(N / 2 – 1)! where r = N / 2
Below is the implementation of the above approach:
Time Complexity: O(N)
Auxiliary Space: O(N)