Next Permutation LeetCode solution in Python

1
class Solution:
2
def nextPermutation(self, nums) -> None:
3
firstDecreasingElement = -1
4
toSwapWith = -1
5
lastIndex = len(nums) - 1
6

7
# Looking for an element that is less than its follower
8
for i in range(lastIndex, 0, -1):
9
if nums[i] > nums[i - 1]:
10
firstDecreasingElement = i - 1
11
break
12

13
# If there is not any then reverse the array to make initial permutation
14
if firstDecreasingElement == -1:
15
for i in range(0, lastIndex // 2 + 1):
16
nums[i], nums[lastIndex - i] = nums[lastIndex - i], nums[i]
17
return
18

19
# Looking for an element to swap it with firstDecreasingElement
20
for i in range(lastIndex, 0, -1):
21
if nums[i] > nums[firstDecreasingElement]:
22
toSwapWith = i
23
break
24

25
# Swap found elements
26
nums[firstDecreasingElement], nums[toSwapWith] = (
27
nums[toSwapWith],
28
nums[firstDecreasingElement],
29
)
30

31
# Reverse elements from firstDecreasingElement to the end of the array
32
left = firstDecreasingElement + 1
33
right = lastIndex
34
while left < right:
35
nums[left], nums[right] = nums[right], nums[left]
36
left += 1
37
right -= 1

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0