imashutosh51

Next Permutation

Feb 4th, 2026 (edited)
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.26 KB | None | 0 0
  1. """
  2. Intuition:
  3. To get the next lexicographically greater permutation, we want to make the smallest possible increase.
  4. Scan from right to find the first index (pivot) where nums[i] < nums[i+1]. This is the first place
  5. where we can increase the number. Then, from the right side, find the smallest element greater than
  6. nums[i] and swap it with the pivot. Finally, reverse the suffix (i+1 to end) to make it the smallest
  7. possible order. If no pivot exists (array is fully non-increasing), reverse the whole array to get
  8. the smallest permutation.
  9.  
  10. Trick: if the array is already sorted in decreasing order,then reverse the array to get the smallest number possible.
  11. """
  12.  
  13.  
  14. class Solution:
  15.     def nextPermutation(self, nums: List[int]) -> None:
  16.         #find pivot element first
  17.         i=len(nums)-2
  18.         while i>=0 and nums[i]>=nums[i+1]:
  19.             i-=1
  20.         #pivot=i,now find the just bigger element than the pivot in the right side of the array and right side is already increasing order
  21.         if i<0:
  22.             nums.reverse()
  23.             return
  24.  
  25.         j=len(nums)-1
  26.         if i>=0:
  27.             while j>i and nums[j]<=nums[i]:
  28.                 j-=1
  29.             nums[j],nums[i]=nums[i],nums[j]
  30.         nums[i+1:]=reversed(nums[i+1:])
  31.  
  32.            
Advertisement
Add Comment
Please, Sign In to add comment