Leetcode Next Permutation in Python
Maybe it is a personal taste, but I don't like introducing a nested function because some code is repeated in a particular case. Maybe a refactoring 
could avoid this. 


first you notice that index is naturally offset by one... refactor it:

index = n - 1
while index &gt; 0 and nums[index-1] &gt;= nums[index]:
    index -= 1
if index == 0:
    swap(0, n - 1)
    return
i = n - 1
while i &gt; index-1 and nums[i] &lt;= nums[index-1]:
    i -= 1
nums[i], nums[index-1] = nums[index-1], nums[i]
swap(index, n - 1)

now you can remove the duplicated call to swap:

if index &gt; 0:
    i = n - 1
    while i &gt; index-1 and nums[i] &lt;= nums[index-1]:
        i -= 1
    nums[i], nums[index-1] = nums[index-1], nums[i]
swap(index, n - 1)

and you can remove the nested function:

n -= 1
while index &lt; n:
    nums[index], nums[n] = nums[n], nums[index]
    index += 1
    n -= 1



This is the resulting code. It is clear that this code is O(n) since there are no nested loops.

def nextPermutation(nums):
    """
    :type nums: List[int]
    :rtype: void Do not return anything, modify nums in-place instead.
    """
    n = len(nums)
    index = n - 1
    while index &gt; 0 and nums[index-1] &gt;= nums[index]:
        index -= 1
    if index &gt; 0:
        i = n - 1
        while i &gt; index-1 and nums[i] &lt;= nums[index-1]:
            i -= 1
        nums[i], nums[index-1] = nums[index-1], nums[i]
    n -= 1
    while index &lt; n:
        nums[index], nums[n] = nums[n], nums[index]
        index += 1
        n -= 1