Number of ways in which an item returns back to its initial position in N swaps in array of size K
Given two numbers K and N, the task is to find the number of ways such that an item at position i returns back to its initial position in an array of length K in N steps, where, in each step, the item can be swapped with any other item in K
Input: N = 2, K = 5
For the given K, lets assume there are 5 positions 1, 2, 3, 4, 5. Since it is given in the question that the item is at some initial position B and the final answer for all B’s is same, lets assume that the item is at position 1 in the beginning. Therefore, in 2 steps (N value):
The item can either be placed at position 2 and again at position 1.
The item can either be placed at position 3 and again at position 1.
The item can either be placed at position 4 and again at position 1.
The item can either be placed at position 5 and again at position 1.
Therefore, there are a total of 4 ways. Hence the output is 4.
Input: N = 5, K = 5
Approach: The idea to solve this problem is to use the concept of combinations. The idea is that at every step, there are K – 1 possibilities to place the item in the next place. To implement this, an array F is used where F[i] represents the number of ways to place the items at position 1 for ‘i’th step. Since it is given that the item doesn’t belong to the person to whom it belonged in the previous step, therefore, the number of ways of the previous step has to be subtracted for every step. Therefore, the array F can be filled as:
F[i] = (K - 1)(i - 1) - F[i - 1]
Finally, the last element of the array F is returned.
Below is the implementation of the approach:
Time Complexity: O(n), as we are using recursive calls to traverse n times.
Auxiliary Space: O(n), as we are using extra space for a recursive stack for our recursive calls.