next permutation

🏠
 1 class Solution:
 2     def nextPermutation(self, perm):
 3         p = len(perm) - 2
 4         while p >= 0 and perm[p] >= perm[p + 1]:
 5             p -= 1
 6         if p != -1:
 7             for i in reversed(range(p + 1, len(perm))):
 8                 if perm[i] > perm[p]:
 9                     perm[p], perm[i] = perm[i], perm[p]
10                     break
11             return perm[: p + 1] + [*reversed(perm[p + 1 :])]
12 
13 
14 Solution().nextPermutation([2, 4, 5, 3, 1]) == [2, 5, 1, 3, 4]
15 Solution().nextPermutation([1, 2, 3]) == [1, 3, 2]
16 Solution().nextPermutation([3, 2, 1]) == [1, 2, 3]
17 Solution().nextPermutation([1, 1, 5]) == [1, 5, 1]