Skip to content
Merged
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions data_structures/arrays/rotate_array.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
from typing import List

Check failure on line 1 in data_structures/arrays/rotate_array.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (I001)

data_structures/arrays/rotate_array.py:1:1: I001 Import block is un-sorted or un-formatted

Check failure on line 1 in data_structures/arrays/rotate_array.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP035)

data_structures/arrays/rotate_array.py:1:1: UP035 `typing.List` is deprecated, use `list` instead

def rotate_array(arr: List[int], k: int) -> List[int]:

Check failure on line 3 in data_structures/arrays/rotate_array.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP006)

data_structures/arrays/rotate_array.py:3:45: UP006 Use `list` instead of `List` for type annotation

Check failure on line 3 in data_structures/arrays/rotate_array.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP006)

data_structures/arrays/rotate_array.py:3:23: UP006 Use `list` instead of `List` for type annotation

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please provide descriptive name for the parameter: k

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Single-letter variable names are uncool, as discussed in CONTRIBUTING.md.

n = len(arr)
if n == 0:
return arr

k = k % n

if k < 0:
k += n

def reverse(start, end):
while start < end:
arr[start], arr[end] = arr[end], arr[start]
start += 1
end -= 1

reverse(0, n - 1)
reverse(0, k - 1)
reverse(k, n - 1)

return arr


if __name__ == "__main__":
examples = [
([1, 2, 3, 4, 5], 2),
([1, 2, 3, 4, 5], -2),
([1, 2, 3, 4, 5], 7),
([], 3),
]

for arr, k in examples:
rotated = rotate_array(arr.copy(), k)
print(f"Rotate {arr} by {k}: {rotated}")
Loading