# My solution by using Python

• ``````class Solution:
# @param nums, a list of integer
# @param k, num of steps
# @return nothing, please modify the nums list in-place.
def rotate(self, nums, k):
n = len(nums)
k = k % n
nums[:] = nums[n-k:] + nums[:n-k]
``````

A little important thing to be cautious:

``````nums[:] = nums[n-k:] + nums[:n-k]
``````

can't be written as:

``````nums = nums[n-k:] + nums[:n-k]
``````

on the OJ.

The previous one can truly change the value of old nums, but the following one just changes its reference to a new nums not the value of old nums.

• a small improvement using negative index:

``````def rotate(self, nums, k):
k = k % len(nums)
nums[:] = nums[-k:] + nums[:-k] ``````

• Yeah, good!
Python is easy to use.

• Does it use O(1) memory space?

• @Jan2003 If I remember it right, python sub-indexing create a copy of the range specified, so I believe the space complexity on this one is O(n). Correct me if I'm wrong.

• @boy27910231 You should be right. Every time we do list slicing, a new copy is created.

• '''
n = len(nums)
k1 = k % len(nums)
nums = nums[n-k1:] + nums[:n-k1]
'''
'''
n = len(nums)
k1 = k % len(nums)
nums = nums[-k1:] + nums[:-k1]
'''
both them works
but
'''
n = len(nums)
k1 = k % len(nums)
nums = nums[-k1:] + nums[:n-k1]
'''
or
'''
n = len(nums)
k1 = k % len(nums)
nums = nums[n-k1:] + nums[:-k1]
'''
they don't work, Can anyone explain?

• This post is deleted!

• @ericsungmi Hey there.

If you could repost by using ``` and not ''' it will be easier to read.

Then I'll see if I can help.

• @drewbie

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

both them works
but

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

or

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

they don't work, Can anyone explain?

• @ericsungmi
is n-k1 not equal -k?

• @ericsungmi I suppose you should figure the difference between nums and nums[:], the question need to do it in-place

• @ericsungmi By using nums[:]=nums[n-k1:] + nums[:-k1] rather than num=...

• @boy27910231 and I want to know the time complexity here, is it O(n) ?

• This post is deleted!

• @Maples7 Learned a new thing! Very Thanks!

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