Skip to content

Commit 5d0e185

Browse files
committed
added rotate_array function
1 parent 3c023b2 commit 5d0e185

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
def rotate_array(arr, k):
2+
"""
3+
Rotates the array to the right by k steps
4+
5+
Args:
6+
arr(list): The input array
7+
k(int): Number of steps to rotate
8+
9+
Returns:
10+
list: Rotated array
11+
"""
12+
n = len(arr)
13+
k = k % n if n else 0
14+
15+
arr.reverse() # Reverse the entire array
16+
arr[:k] = reversed(arr[:k]) # Reverse the first k elements
17+
arr[k:] = reversed(arr[k:]) # Reverse the last (n-k) elements
18+
19+
return arr
20+
21+
22+
if __name__ == "__main__":
23+
arr = [1, 2, 3, 4, 5, 6, 7, 8]
24+
k = 3
25+
print("Rotated array: ", rotate_array(arr, k))

0 commit comments

Comments
 (0)