Next Permutation in Python


Suppose we want to implement the next permutation method, that method rearranges numbers into the lexicographically next greater permutation of numbers. If such arrangement is not possible, this method will rearrange it as the lowest possible order (That is actually, sorted in ascending order). The replacement must be in-place and do not use any extra memory. For example, if the Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.

1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1

Let us see the steps −

  • found := false, i := length of the array – 2
  • while i >= 0
    • if A[i] < A[i + 1], then found := True, and terminate the loop
    • increase i by 1
  • if found := false, then sort the array A,
  • otherwise
    • m := find maximum element index from index i + 1, from A, and from the current element A[i]
    • swap the elements A[i] and A[m]
    • reverse all the elements from i+1 to the end in A

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution(object):
   def nextPermutation(self, nums):
      found = False
      i = len(nums)-2
      while i >=0:
         if nums[i] < nums[i+1]:
            found =True
            break
         i-=1
      if not found:
         nums.sort()
      else:
         m = self.findMaxIndex(i+1,nums,nums[i])
         nums[i],nums[m] = nums[m],nums[i]
         nums[i+1:] = nums[i+1:][::-1]
      return nums
   def findMaxIndex(self,index,a,curr):
      ans = -1
      index = 0
      for i in range(index,len(a)):
         if a[i]>curr:
            if ans == -1:
               ans = curr
               index = i
            else:
               ans = min(ans,a[i])
               index = i
      return index
ob1 = Solution()
print(ob1.nextPermutation([1,2,5,4,3]))

Input

[1,2,5,4,3]

Output

[1, 3, 2, 4, 5]

Updated on: 04-May-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements