I am doing some stuff on leetcode and came up with solution it works fine but some cases. Here is the problem itself:
But in case like this it doesn't:
It doesn't make sense how can I rotate elements if k is bigger than length of array. If you have any idea how to improve this solution I would be grateful
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
if len(nums) > k:
self.swap(nums, 0, len(nums)-1)
self.swap(nums, 0,k-1)
self.swap(nums, k, len(nums)-1)
def swap(self, nums, start, end):
while start < end:
nums[start], nums[end] = nums[end], nums[start]
start+=1
end-=1


In order to understand why this doesn't work for the cases where
kis larger than the array length, let me try to explain some of the logic behind rotating by such values ofk.The modulo operator,
%will be useful. For example, if an array is 5 long, and you want to rotate by 5, you end up with the same array. So technically, you'd optimally want to rotate by 0. This is where the%operator comes into play.5 % 5 = 0. If we want to rotate an array length 5 by 7 spots, we would end up with the same thing as rotating the array by 2, and it turns out that7 % 5 = 2. Do you see where I am going with this?This also holds true if the value of
kis less than the length of the array. Say we want to rotate an array length 5 by 3, we do3 % 5 = 3.So for any rotation of amount
kand array lengthL, optimization rotation amountnis equivalent ton = k % L.You should modify your code at the beginning of your rotate method to adjust the rotation amount:
and use this value to rotate the correct amount.