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


  • 2
    G

    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]

  • 0
    Z
    This post is deleted!

  • 0
    Z

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


  • 0
    G

    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[:])


  • 0
    Y

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


  • 0
    G

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


  • 2
    J

    I think your solution is O(n) space


Log in to reply
 

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