Simple and Elegant, 2-Line Python Solution


  • 0
    Y

    Think of the array as a physical loop - the end and the start of the array is connected, and by whatever number of steps the array rotates, every time an element is pushed beyond the end of the array returns at the start of the array - therefore:
    '''
    class Solution(object):
    def rotate(self, nums, k):

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

    '''
    Divide k by the length of the array and get the remainder, incase k is larger than the length of the array (rotate around the array multiple times). Then concatenate the elements that circles to the beginning of the array and whats left in the array.


Log in to reply
 

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