Skip to content

Commit 0e2a9d2

Browse files
authored
Merge pull request #134 from dsrao711/issue_131
Python solution for next permutation
2 parents 5687077 + e4ccb57 commit 0e2a9d2

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

DSA 450 GFG/next_permutation.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# Link for the problem : https://leetcode.com/problems/next-permutation/
2+
3+
4+
class Solution(object):
5+
6+
def nextPermutation(self, nums):
7+
found = False
8+
i = len(nums)-2
9+
while i >=0:
10+
if nums[i] < nums[i+1]:
11+
found =True
12+
break
13+
i-=1
14+
if not found:
15+
nums.sort()
16+
else:
17+
m = self.findMaxIndex(i+1,nums,nums[i])
18+
nums[i],nums[m] = nums[m],nums[i]
19+
nums[i+1:] = nums[i+1:][::-1]
20+
return nums
21+
22+
def findMaxIndex(self,index,a,curr):
23+
ans = -1
24+
index = 0
25+
for i in range(index,len(a)):
26+
if a[i]>curr:
27+
if ans == -1:
28+
ans = curr
29+
index = i
30+
else:
31+
ans = min(ans,a[i])
32+
index = i
33+
return index
34+
ob1 = Solution()

0 commit comments

Comments
 (0)