My LeetCode Notes with Python— Array Rotation

Yili Hsu
2 min readNov 21, 2021

Things that I should avoid when writing python

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

Example 1:

Input: nums = [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
Explanation:
rotate 1 steps to the right: [7,1,2,3,4,5,6]
rotate 2 steps to the right: [6,7,1,2,3,4,5]
rotate 3 steps to the right: [5,6,7,1,2,3,4]

This problem require us to modify the input array nums, instead of assign to a new one. So we’ll need to change the value in the given array.

Wrong behavior

My first try was directly assign the rotated list to the array nums.

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

However, it failed to pass the Submission. Because If you assign something to the variable nums, it will from then on point to the new address. The address it pointed to before that assignment (your original list) will stay unchanged. If you, instead, assign to elements of nums, this will change the original list as expected.

This also happens with deepcopy and copy function, so make sure you assign to the elements if you want to change the input array.

The correct code should be like this

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

Assign to the elements will not change the address but the value only.

Keep this in mind as this may affect your program when passing lists!

--

--

Yili Hsu

A CS student from Taiwan who loves traveling, cooking and playing with cats.