Leetcode Next Permutation in Python My solution to Leetcode Next Permutation in Python. 


  Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
  
  If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
  
  The replacement must be in-place and use only constant extra memory.
  
  Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
  
  1,2,3 → 1,3,2
  3,2,1 → 1,2,3
  1,1,5 → 1,5,1


Q:if the following code is Big \$O(N)\$.

def nextPermutation(self, nums):
    """
    :type nums: List[int]
    :rtype: void Do not return anything, modify nums in-place instead.
    """
    def swap(i, j):
        while i &lt; j:
            nums[i], nums[j] = nums[j], nums[i]
            i += 1
            j -= 1

    n = len(nums)
    index = n - 2
    while index &gt; -1 and nums[index] &gt;= nums[index + 1]:
        index -= 1
    if index == -1:
        swap(0, n - 1)
        return
    i = n - 1
    while i &gt; index and nums[i] &lt;= nums[index]:
        i -= 1
    nums[i], nums[index] = nums[index], nums[i]
    swap(index + 1, n - 1)
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