Uncategorized

arrays – Unable to comprehend this behaviour of swapping statement in Python


I was solving a question on leetcode. “41. First Missing Positive”

For swapping, when I used nums[i],nums[nums[i]-1] = nums[nums[i]-1],nums[i] , I got TLE.

But nums[nums[i]-1],nums[i] = nums[i],nums[nums[i]-1] is working perfectly.

This is not just the case with leetcode.

I tried to understand the difference, spent 1 hour on the problem.
And then reached out to Google bard and Chatgpt. Both struggled.

After spending lots of time, I got an answer “Given that both codes share the same logic and conditional statements, it remains puzzling why Code 1 is exhibiting an issue, especially in the scenario you described with the infinite loop.”

Here is my code:

class Solution:
    def firstMissingPositive(self, nums: List[int]) -> int:
        i,n = 0,len(nums)

        while i<n:
            if nums[i]>0 and nums[i]<=n and nums[nums[i]-1]!=nums[i]:
                #nums[i],nums[nums[i]-1] = nums[nums[i]-1],nums[i]
                nums[nums[i]-1],nums[i] = nums[i],nums[nums[i]-1]

            else:
                i+=1
        for i in range(n):
            if nums[i]!=i+1:
                return i+1
        return n+1
        

The commented out statement is giving TLE , but second one is working fine. Can someone please explain, what is causing this? Is a,b=b,a and b,a=a,b different?

I also defined the function in Python IDLE, added a print statement below the swapping statement, and it got stuck in infinite loop again.

Defined function in Python IDLE

Output (infinite loop)

TLE with first statement

Accepted with second statement



Source link

Leave a Reply

Your email address will not be published. Required fields are marked *