Skip to content

Commit 02f2a78

Browse files
committed
added rotate_array.py
1 parent 9372040 commit 02f2a78

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
def rotate_array(arr, k):
2+
n = len(arr)
3+
if n == 0:
4+
return arr
5+
6+
k = k % n
7+
8+
if k < 0:
9+
k += n
10+
11+
def reverse(start, end):
12+
while start < end:
13+
arr[start], arr[end] = arr[end], arr[start]
14+
start += 1
15+
end -= 1
16+
17+
reverse(0, n - 1)
18+
reverse(0, k - 1)
19+
reverse(k, n - 1)
20+
21+
return arr
22+
23+
24+
if __name__ == "__main__":
25+
examples = [
26+
([1, 2, 3, 4, 5], 2),
27+
([1, 2, 3, 4, 5], -2),
28+
([1, 2, 3, 4, 5], 7),
29+
([], 3),
30+
]
31+
32+
for arr, k in examples:
33+
rotated = rotate_array(arr.copy(), k)
34+
print(f"Rotate {arr} by {k}: {rotated}")

0 commit comments

Comments
 (0)