-
-
Notifications
You must be signed in to change notification settings - Fork 48.7k
added rotate_array.py #13336
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
added rotate_array.py #13336
Changes from 7 commits
02f2a78
ded9c6d
7096968
302988d
bd4e433
925cb2d
85eb704
7043856
889aa02
90b332b
8aa6469
ec22c92
5a1cf10
79dc1ad
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
from typing import List | ||
|
||
|
||
def rotate_array(arr: List[int], k: int) -> List[int]: | ||
Check failure on line 4 in data_structures/arrays/rotate_array.py
|
||
cclauss marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
n = len(arr) | ||
if n == 0: | ||
return arr | ||
|
||
k = k % n | ||
|
||
if k < 0: | ||
k += n | ||
|
||
def reverse(start: int, end: int) -> None: | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. As there is no test file in this pull request nor any test function or class in the file |
||
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}") |
Uh oh!
There was an error while loading. Please reload this page.