Skip to main content

189. Rotate Array - LeetCode

ยท One min read
class Solution1:
def rotate(self, nums: list[int], k: int) -> None:
if len(nums) > 1:
k %= len(nums)
nums[:-k], nums[-k:] = nums[-k:], nums[:-k]


class Solution:
def rotate(self, nums: list[int], k: int) -> None:
def reverse(start, stop):
for i in range((stop - start) // 2):
l, r = start + i, stop - 1 - i
nums[l], nums[r] = nums[r], nums[l]

k %= len(nums)
reverse(0, len(nums) - k)
reverse(len(nums) - k, len(nums))
reverse(0, len(nums))