Lexicographic rank of a string using STL
You are given a string, find its rank among all its permutations sorted lexicographically.
Examples:
Input : str[] = "acb"
Output : Rank = 2
Input : str[] = "string"
Output : Rank = 598
Input : str[] = "cba"
Output : Rank = 6
We have already discussed solutions to find Lexicographic rank of string In this post, we use the STL function “next_permutation ()” to generate all possible permutations of the given string and, as it gives us permutations in lexicographic order, we will put an iterator to find the rank of each string. While iterating when Our permuted string becomes identical to the original input string, we break from the loop and the iterator value for the last iteration is our required result.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
int findRank(string str)
{
string orgStr = str;
sort(str.begin(), str.end());
long int i = 1;
do {
if (str == orgStr)
break ;
i++;
} while (next_permutation(str.begin(), str.end()));
return i;
}
int main()
{
string str = "cba" ;
cout << findRank(str);
return 0;
}
|
Java
Python3
import itertools
def findRank( str ):
orgStr = ''.join( sorted ( str ))
d = []
i = 1
for permutation in itertools.permutations(orgStr):
if permutation not in d:
d.append(permutation)
if ''.join(permutation) = = str :
break
i + = 1
return i
if __name__ = = '__main__' :
str = 'bca'
print (findRank( str ))
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static int FindRank( string str)
{
string orgStr = new string (str.OrderBy(c => c).ToArray());
HashSet< string > set = new HashSet< string >();
int i = 1;
foreach ( var permutation in Permutations(orgStr))
{
if (! set .Contains(permutation))
{
set .Add(permutation);
if (permutation == str)
{
break ;
}
i++;
}
}
return i;
}
static IEnumerable< string > Permutations( string str)
{
if (str.Length == 1)
{
yield return str;
}
else
{
foreach ( var ch in str)
{
foreach ( var permutation in Permutations(str.Remove(str.IndexOf(ch), 1)))
{
yield return ch + permutation;
}
}
}
}
static void Main( string [] args)
{
string str = "bca" ;
Console.WriteLine(FindRank(str));
}
}
|
Javascript
function findRank(str) {
const MOD = 1000003;
const n = str.length;
let rank = 1;
let factorial = 1;
for (let i = 0; i < n; i++) {
let smaller = 0;
for (let j = i + 1; j < n; j++) {
if (str[j] < str[i]) {
smaller++;
}
}
rank = (rank + (smaller * factorial)) % MOD;
factorial = (factorial * (n - i)) % MOD;
}
return rank;
}
const str = "cba" ;
console.log(findRank(str));
|
Time Complexity: O(n log n)
Auxiliary Space: O(1)
This article is contributed by Aarti_Rathi and Shivam Pradhan (anuj_charm).
Last Updated :
26 Oct, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...