- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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]
- Related Articles
- Lexicographically next permutation in C++
- Program to get next integer permutation of a number in C++
- Permutation and Combination in Python?
- Previous Permutation With One Swap in Python
- Generate all permutation of a set in Python?
- Program to find decode XORed permutation in Python
- Python Program for BogoSort or Permutation Sort
- Program to find next state of next cell matrix state in Python?
- Python program for permutation of a given string inbuilt function in python
- Find n-th lexicographically permutation of a strings in Python
- Find next sibling element in Selenium, Python?
- Python program for the permutation of a given string inbuilt function in python
- Permutation of a given string using the inbuilt function in Python
- Program to find maximum sum obtained of any permutation in Python
- Permutation Sequence in C++

Advertisements