Skip to content

Instantly share code, notes, and snippets.

@athulmurali
Created July 3, 2019 03:25
Show Gist options
  • Save athulmurali/0ed2144c6114cce7dded929b0988c615 to your computer and use it in GitHub Desktop.
Save athulmurali/0ed2144c6114cce7dded929b0988c615 to your computer and use it in GitHub Desktop.
nextPermutation
class Solution:
def nextPermutation(self, nums: List[int]) -> None:
n = len(nums)
prev = -float("inf")
ind = n -1
for i in range(n):
ind = n - i -1
if nums[ind] < prev:
j = n -1
while(nums[j] <= nums[ind] and j > ind) :
j -=1
# swap current ind element with next greatest element to current_ind of all the elements to the right of current ind
nums[j], nums[ind] = nums[ind] , nums[j]
#sort current ind + 1 to right end
nums[ind + 1: ] = sorted(nums[ind + 1: ])
return
else:
prev = nums[ind]
if ind == 0:
nums.sort()
@athulmurali
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment