![]() |
VOOZH | about |
Permutation refers to the process of arranging all the members of a given set to form a sequence. The number of permutations on a set of n elements is given by n! , where "!" represents factorial.
The Permutation Coefficient represented by P(n, k) is used to represent the number of ways to obtain an ordered subset having k elements from a set of n elements.
Mathematically it's given as:
Image Source : Wiki
Examples :
P(10, 2) = 90
P(10, 3) = 720
P(10, 0) = 1
P(10, 1) = 10
The coefficient can also be computed recursively using the below recursive formula:
P(n, k) = P(n-1, k) + k* P(n-1, k-1) The recursive formula for permutation-coefficient is :
P(n, k) = P(n-1, k) + k* P(n-1, k-1)
But how ??
here is the proof,
We already know,
The binomial coefficient is nCk =
k! (n-k)!
and, permutation-coefficient nPr =
(n-k)!
So, I can write
nCk =
k!
=> k! * nCk = nPk —------------------- eq.1
The recursive formula for the Binomial coefficient nCk can be written as,
nCk(n,k) = nCk(n-1,k-1) + nCk(n-1,k) you can refer to the following article for more details
https://www.geeksforgeeks.org/dsa/binomial-coefficient-dp-9/
Basically, it makes use of Pascal's triangle which states that in order to fill the value at nCk[n][k] you need the summation of nCk[n-1][k-1] and nCk[n-1][k] along with some base cases. i.e,
nCk[n][k] = nCk[n-1][k-1]+nCk[n-1][k].
nCk[n][0] = nCk[n][n] = 1 (Base Case)
Anyways, let's proceed with our eq.1
=> k! * nCk = nPk
=> k! * ( nCk(n-1,k-1) + nCk(n-1,k) ) = nPk [ as, nCk = nCk(n-1,k-1)+nCk(n-1,k) ]
=> k! * ( + ) = nPk
((n-1)-(k-1))! * (k-1)! (n-1-k)! * k!
=> + = nPk
((n-1)-(k-1))! * (k-1)! (n-1-k)! * k!
=> + = nPk [ as, k! = k*(k-1)! ]
((n-1)-(k-1))! * (k-1)! (n-1-k)! * k!
=> + = nPk
((n-1)-(k-1))! (n-1-k)!
can be replaced by nPk(n-1,k-1) as per the permutation-coefficient
((n-1) - (k-1))!
Similarly, can be replaced by nPk(n-1,k).
(n-1-k)!
Therefore,
=> k * nPk(n-1, k-1) + nPk(n-1, k) = nPk
Finally, that is where our recursive formula came from.
P(n, k) = P(n-1, k) + k* P(n-1, k-1)
If we observe closely, we can analyze that the problem has an overlapping substructure, hence we can apply dynamic programming here. Below is a program implementing the same idea.
Output :
Value of P(10, 2) is 90 Here as we can see the time complexity is O(n*k) and space complexity is O(n*k) as the program uses an auxiliary matrix to store the result.
Can we do it in O(n) time ?
Let us suppose we maintain a single 1D array to compute the factorials up to n. We can use computed factorial value and apply the formula P(n, k) = n! / (n-k)!. Below is a program illustrating the same concept.
Output :
Value of P(10, 2) is 90 A O(n) time and O(1) Extra Space Solution
Output :
Value of P(10, 2) is 90
Thanks to Shiva Kumar for suggesting this solution.