# Python_The same code, One is passed, the other is TLE. (a little difference between the swap expression)

• First TLE:

``````        if not nums:
return 1
for i in xrange(len(nums)):
while 1 <= nums[i] <= len(nums) and nums[i] != nums[nums[i]-1]:
nums[i],nums[nums[i]-1] = nums[nums[i]-1],nums[i]
for i in xrange(len(nums)):
if nums[i] != i+1:
return i+1
return nums[-1]+1
``````

Second Passed

``````    if not nums:
return 1
for i in xrange(len(nums)):
while 1 <= nums[i] <= len(nums) and nums[i] != nums[nums[i]-1]:
nums[nums[i]-1],nums[i] = nums[i],nums[nums[i]-1]
for i in xrange(len(nums)):
if nums[i] != i+1:
return i+1
return nums[-1]+1
``````

I have checked the docs in python:https://docs.python.org/2/reference/expressions.html#evaluation-order
but I cannot see why.

BTW, the test result for the first solution is okay.

• The first one:

``````nums[i],nums[nums[i]-1] = nums[nums[i]-1],nums[i]
``````

After nums[i] = nums[nums[i]-1], nums[i]-1 is no longer the same value. So you are setting nums[i] to the wrong index. You may want to back up nums[i]-1:

``````c = nums[i] - 1
nums[i], nums[c] = nums[c], nums[i]``````

• Thanks for your answer, but why the second version of code is passed?

• In python, we can use p,q = q,p to swap the value between two variables, but it doesn't work in the first situation, I don't know why~~

• For the second answer, nums[nums[i]-1] won't affect the value of i, so nums[i] = xxx is still correct.

• I guess I got It! Thanks~ so assume there is an arrayA[] we have A[p],A[A[p]+q] = A[A[p]+q],A[p] this operation cannot swap their value right?

• That's correct. Since A[p] has changed, A[p]+q is no longer the A[p]+q as before.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.