# Simple Python solution - O(k) + O(1)

• The algorithm is easy: we just swap the last k elements with the first n-k elements ...

``````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):
if not nums or not k:
return None

k %= len(nums)

if k:
nums[:k], nums[k:] = nums[-k:], nums[:-k]``````

• This post is deleted!

• Quick question: what's the difference between num and num[:] ? Thanks!

• num[:] will make a new copy of the original list (aka it is a deep copy of the original list, num[:] will return a different object)

try this:
num = [1,2,3]
print id(num), id(num[:])

• How to understand this "nums[:k], nums[k:] = nums[-k:], nums[:-k]"? Is it updating the original object or creating a new object?

• This will mutate the list in place (aka updating the original object)

• I think your solution is O(n) space

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