-
-
Notifications
You must be signed in to change notification settings - Fork 49.3k
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 4 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,36 @@ | ||
| from typing import List | ||
|
Check failure on line 1 in data_structures/arrays/rotate_array.py
|
||
|
|
||
| def rotate_array(arr: List[int], k: int) -> List[int]: | ||
|
Check failure on line 3 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, end): | ||
jenyyy4 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
jenyyy4 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| 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.