Skip to content

Instantly share code, notes, and snippets.

@kushpvo
Created April 29, 2024 08:15
Show Gist options
  • Save kushpvo/a49d2712fa18213a06b94d131041b6ea to your computer and use it in GitHub Desktop.
Save kushpvo/a49d2712fa18213a06b94d131041b6ea to your computer and use it in GitHub Desktop.
rotateArray
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
k = k % len(nums)
# Reversing the whole array 12345 -> 54321
l, r = 0, len(nums) - 1
while l < r:
nums[l], nums[r] = nums[r], nums[l]
l, r = l + 1, r - 1
# reverse first part where end is k
l, r = 0, k - 1
while l < r:
nums[l], nums[r] = nums[r], nums[l]
l, r = l + 1, r - 1
# reverse the remaining part
l, r = k, len(nums) - 1
while l < r:
nums[l], nums[r] = nums[r], nums[l]
l, r = l + 1, r - 1
@kushpvo
Copy link
Author

kushpvo commented Apr 29, 2024

Toolkit: Reverse elements of array

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment