We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 9372040 commit 02f2a78Copy full SHA for 02f2a78
data_structures/arrays/rotate_array.py
@@ -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
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