0

I have been trying to do the following problem on leetcode

I did solve it - and when I am printing out my results, it is correct. However, the output of the problem is still incorrect (though it is the same variable...) I think it is because the problem asks to do everything in-place - and I assumed I did it.

My code is here:

class Solution:
def nextPermutation(self, nums: List[int]) -> None:
    """
    Do not return anything, modify nums in-place instead.
    """
    k = len(nums) - 1
    i = - 100
    while k > 0:
        if nums[k - 1] < nums[k]:
            i = k
            break
        else:
            k -=1
    if i > 0:
        iterator = i - 1
        while iterator <= len(nums) - 1:
            if iterator == len(nums) - 1 or (nums[iterator] > nums[i-1] and nums[iterator + 1] < nums[i-1] ):
                nums = self.swap(nums,i-1,iterator)
            iterator += 1
        nums = nums[:i] + sorted(nums[i:])
        print(nums) #HERE THE PRINTED ANSWER IS CORRECT
    else:
        nums.sort()
        return
    

def swap(self,nums,i,j):
    temp = nums[i]
    nums[i] = nums[j]
    nums[j] = temp
    return nums

The output I am getting:

Output

So my main question is why the output value and the stout of the same variable are different? Is there a way to fix it?

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
poisonedivy
  • 479
  • 4
  • 7

1 Answers1

1

I guess you are right. You should not return nums. You can try solving the problem with your method using nums[:], if you want.

This solution would pass though. There are about 50 questions like that, which they ask for in-place returns or changing the input as is.

class Solution:
    def nextPermutation(self, nums):
        i = j = len(nums) - 1
        while i > 0 and nums[i - 1] >= nums[i]:
            i -= 1
        if i == 0:
            nums.reverse()
            return

        k = i - 1
        while nums[j] <= nums[k]:
            j -= 1

        nums[k], nums[j] = nums[j], nums[k]
        left, right = k + 1, len(nums) - 1
        while left < right:
            nums[left], nums[right] = nums[right], nums[left]
            left += 1
            right -= 1

References

  • For additional details, you can see the Discussion Board. There are plenty of accepted solutions, explanations, efficient algorithms with a variety of languages, and time/space complexity analysis in there.
Emma
  • 27,428
  • 11
  • 44
  • 69
  • 1
    Unfortunately, there is no explanation for the sorting part of the array in-place on leetcode discussion forums. What would be the intuition for swapping process you have in the code above? – poisonedivy Jun 26 '20 at 16:17