Skip to content

Commit

Permalink
Re-solve "Rotate Array"
Browse files Browse the repository at this point in the history
  • Loading branch information
lancelote committed Feb 5, 2024
1 parent 147157c commit 69e9e4d
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 10 deletions.
24 changes: 14 additions & 10 deletions src/rotate_array.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
def reverse(nums: list[int], left: int, right: int) -> None:
while left < right:
nums[left], nums[right] = nums[right], nums[left]
left += 1
right -= 1
def reverse(start: int, end: int, array: list[int]) -> None:
n = end - start

for i in range(n // 2):
left = start + i
right = end - i - 1

array[left], array[right] = array[right], array[left]


class Solution:
def rotate(self, nums: list[int], k: int) -> None:
"""Mutates in place."""
k %= len(nums)
reverse(nums, 0, len(nums) - 1)
reverse(nums, 0, k - 1)
reverse(nums, k, len(nums) - 1)
n = len(nums)
k = k % n

reverse(0, n - k, nums)
reverse(n - k, n, nums)
reverse(0, n, nums)
1 change: 1 addition & 0 deletions tests/test_rotate_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
[
([1, 2, 3, 4, 5, 6, 7], 3, [5, 6, 7, 1, 2, 3, 4]),
([-1, -100, 3, 99], 2, [3, 99, -1, -100]),
([1, 2, 3, 4, 5, 6], 11, [2, 3, 4, 5, 6, 1]),
],
)
def test_solution(nums, k, expected):
Expand Down

0 comments on commit 69e9e4d

Please sign in to comment.