Created
April 29, 2024 08:15
-
-
Save kushpvo/a49d2712fa18213a06b94d131041b6ea to your computer and use it in GitHub Desktop.
rotateArray
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Toolkit: Reverse elements of array