Repository navigation
Expand file tree
/
Copy pathLexiRankPermuteString.cpp
More file actions
100 lines (79 loc) · 1.9 KB
/
Copy pathLexiRankPermuteString.cpp
File metadata and controls
100 lines (79 loc) · 1.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/*
Given a string, S find the rank of the string amongst all its permutations sorted lexicographically.The rank can be big. So print it modulo 1000003.
Note: Return 0 if the characters are repeated in the string.
Example 1:
Input: S = "abc"
Output: 1
Explaination: It is the smallest
lexicographically string of the permutation.
Example 2:
Input: S = "acb"
Output: 2
Explaination: This is the second smallest
lexicographically string of the permutation.
*/
#include <bits/stdc++.h>
using namespace std;
class Solution{
public:
int fact(int i)
{
if (i <= 1) return 1;
else return i*fact(i-1);
}
int rank(string s){
// code here
string k =s;
sort(k.begin() , k.end());
unordered_set<char>st;
for(char ch:k) st.insert(ch);
if(s.size()!=st.size())
return 0;
int chArr[256]={0};
int n=s.length();
int mul=fact(n);
for(int i=0;i<n;i++)
chArr[s[i]]++;
for(int i=1;i<256;i++)
chArr[i]+=chArr[i-1];
int res=1;
for(int i=0;i<n-1;i++)
{
mul=mul/(n-i);
res+=chArr[s[i]-1]*mul;
for(int j=s[i];j<256;j++)
chArr[j]--;
}
return res%1000003;
}
};
// { Driver Code Starts.
int main(){
int t;
cin>>t;
while(t--){
string S;
cin>>S;
Solution ob;
cout<<ob.rank(S)<<endl;
}
return 0;
} // } Driver Code Ends
//ALITER APPROACH
//-----> Inbuild next_permutation method <----------//
int rank(string S)
{
string k =S;
sort(k.begin() , k.end());
unordered_set<char>s;
for(char ch:k) s.insert(ch);
if(S.size()!=s.size()) return 0;
int ans=1;
while(k!=S)
{
next_permutation(k.begin() , k.end());
ans++;
ans=ans%1000003;
}
return ans%1000003;
}