Skip to content

Commit 5f75ef2

Browse files
committed
added pandit's algorithm
1 parent 08c4def commit 5f75ef2

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
+44
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
# -*- coding: utf-8 -*-
2+
"""
3+
Created on Tue Oct 15 18:11:37 2019
4+
5+
@author: Vidhan Jhawar
6+
"""
7+
8+
'''
9+
Narayana Pandit's algorithm to find next lexicographically greatest permutation
10+
11+
Algorithm:
12+
1. Find the largest index k such that a[k] < a[k + 1]. If no such index exists, the permutation is the last permutation.
13+
2. Find the largest index l greater than k such that a[k] < a[l].
14+
3. Swap the value of a[k] with that of a[l].
15+
4. Reverse the sequence from a[k + 1] up to and including the final element a[n].
16+
'''
17+
18+
import math
19+
20+
def nextGreater(w):
21+
w=list(w)
22+
l=len(w)
23+
flag=1
24+
for i in range(l-2,-1,-1):
25+
if(w[i]<w[i+1]):
26+
flag=0
27+
break
28+
if(flag==1):
29+
return 'no answer'
30+
for j in range(l-1,i,-1):
31+
if(w[j]>w[i]):
32+
break
33+
temp=w[i]
34+
w[i]=w[j]
35+
w[j]=temp
36+
for k in range(i+1,math.ceil((l+i-1)/2)+1):
37+
temp=w[k]
38+
w[k]=w[l-k+i]
39+
w[l-k+i]=temp
40+
return ''.join(w)
41+
42+
if __name__ == '__main__':
43+
w=input()
44+
print(nextGreater(w))

0 commit comments

Comments
 (0)