0

Question Reference: https://leetcode.com/problems/rotate-array/

I'm working on Leetcode Question 189. Rotate Array and I solved it by studying other coders' solutions. But new to coding, I still have some questions still and hope someone can help clarify these:

#1 Solution - This works:

k %= len(nums)
nums[:] = nums[-k:] + nums[0:-k]

#2 Solution - This doesn't:

k %= len(nums)
nums = nums[-k:] + nums[0:-k] 
#gives me the original nums which didn't change

But I tried #2 Solution in some Python online IDE, nums did change and gave back the same result as #1 Solution. Why didn't it work in Leetcode?

Another question I have is - the question requires "modify nums in-place", which in my understanding is to perform the operation without using any additional memory. But in #1 Solution, we create a shallow copy of nums by using nums[:], does it meet the requirement?

Thanks!

Jadeyyy
  • 39
  • 7
  • Doesn't `x[:] = ...` just replace the contents of the `x` value without creating a new array? If you create a new array and assign it to the same variable, the old array hasn't been replaced. It's still there. – tadman Jan 13 '23 at 19:30
  • 1
    @tadman Yes it does. – ruohola Jan 13 '23 at 19:30
  • 2
    From the comment in the Python Leetcode i.e. *rtype: None Do not return anything, modify nums in-place instead*, Leetcode is only examining the original array, thus only an inplace solution will be evaluated correctly by Leetcode. The 2nd solution creates a new array that is not examined by Leetcode. – DarrylG Jan 13 '23 at 19:43
  • See also https://stackoverflow.com/q/986006/5987 – Mark Ransom Jan 13 '23 at 20:13
  • 1
    P.S. `[:]` on the right side of the equals sign will create a copy but on the left side it doesn't. – Mark Ransom Jan 13 '23 at 20:15

1 Answers1

0

With nums[:] you just replece the old array values without creating a new one and the error I guess is given because of the requirement.

Hope thats help.

marick
  • 109
  • 6