Given string str with unique characters and a number N, the task is to find the N-th lexicographic permutation of the string using Factoradic method.
Input: str = “abc”, N = 3
All possible permutations in sorted order: abc, acb, bac, bca, cab, cba
3rd permutation is bac
Input: str = “aba”, N = 2
All possible permutations in sorted order: aab, aba, baa
2nd permutation is aba
Approach: The idea is to use the concept of factoradic representation. The main concept of factoradic method is to calculate the sequence of a number. The following are the steps to find the N-th lexicographic permutation using factoradic method:
- Decrement N by 1 because this method considers sorted order as the 0th permutation.
- Divide N with 1 to the length of the string and each time store the remainder in a stack while updating the value of N as N/i.
- The calculated remainder in every step is the factoradic number. So, after calculating the final factoradic representation, start appending the element in the result string which is present on the position.
- Remove the element from the stack on each iteration.
- Repeat the above three steps until the stack becomes empty.
Let’s understand this method with an example. Let the string str be “abcde” and N be 11. Then:
- Initially, 1 is subtracted from N.
N = 11 - 1 N = 10
- Now, at every iteration, divide N with i where i ranges from 1 to the length and store the remainder in a stack:
divide Remainder Quotient Factoradic 10%1 0 10 0 10%2 0 5 00 5%3 2 1 200 2%4 1 0 1200 2%5 0 0 01200
- Now, append the elements into the resultant string from the stack and continuously remove the elements from the stack. Here, the Factoradic representation of the given number is 01200. Therefore:
=a <- Selected =b =d =e =f result = a =b =c <- Selected =d =e result= ac =b =d =e <-Selected result= ace =b <- Selected =d result= aceb =d <-selected result =acebd
- Therefore, the 11th permutation of the string is “acebd”.
Below is the implementation of the above approach:
Note: An approach to find the Nth permutation with the repeating characters is discussed in this article.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.