0

I was solving the Rotate Array leetcode problem:

Given an array, rotate the array to the right by k steps, where k is non-negative.

I tested the following code on my computer (and it seems to do the required job):

nums = [1,2,3,4,5,6,7]
k = 3
nums = nums[-k:] + nums[:len(nums)-k]
print(nums)

>> [5,6,7,1,2,3,4]

Therefore, I tried the following solution:

class Solution:
    def rotate(self, nums: List[int], k: int) -> None:
        nums = nums[-k:] + nums[:len(nums)-k]

However, getting the following test case wrong: enter image description here

Actually, this test case was tested successfully when I ran without defining any function (which I provided above). Yet, really, it didn't work when I defined a special function to rotate. Then, I concluded that I might be doing something wrong when defining the function.

halfer
  • 19,824
  • 17
  • 99
  • 186
VIVID
  • 555
  • 6
  • 14

1 Answers1

2
nums = nums[-k:] + nums[:len(nums)-k]

just rebinds the local variable nums, it does not mutate the original object that nums was referring to before. Do the following instead:

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

Since slice assignment is a mutation on the object referred to by nums, the rotation will affect the list object that was passed to the function.

user2390182
  • 72,016
  • 6
  • 67
  • 89