Rotate Array Leetcode Python Solution

Question

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

Python Solution

class Solution:
    def rotate(self, nums: List[int], k: int) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        if k==0:
            return
        if k>=len(nums):
            k = k % len(nums)
        print('k:',k)
        right_list = nums[-k:] if k>0 else []
        left_list = nums[0:len(nums)-k]
        print('right_list:',right_list)
        print('left_list:',left_list)
        nums[:] = right_list + left_list

Cracking the Coding Interview: 189 Programming Questions and Solutions

Unknown's avatar

Author: mathtuition88

Math and Education Blog

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.