In the array rotation question on Leetcode, why do they just use k %= len(nums)?
def rotate(nums, k):
k %= len(nums)
for i in range(k):
previous = nums[-1]
for j in range(len(nums)):
nums[j], previous = previous, nums[j]
return nums
CodePudding user response:
If you rotate an array by n
where n == len(array)
you are effectively creating the same array as follows:
arr = [1,2,3]
k = 3
1. [3,1,2]
2. [2,3,1]
3. [1,2,3] # as you can see, this array is the same as the original
This implies that we can just avoid redundant rotations and only rotate by k % len(arr)
.
Example:
arr = [1,2,3]
k = 5
1. [3,1,2]
2. [2,3,1]
3. [1,2,3] # this equals the original
4. [3,1,2] # this equals step 1
5. [2,3,1] # this equals step 2
# Since 5 % len(arr) = 5 % 3 = 2
# and since step 5 is the same as step 2
# we can avoid the redundant repetition
# and go for k % len(arr) = 2 from the start