-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrortate_array.py
More file actions
34 lines (25 loc) · 902 Bytes
/
rortate_array.py
File metadata and controls
34 lines (25 loc) · 902 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
"""
given an array, rotate it to the left by d elements.
Solution
-reverse from the first index to the d-1th index
-reverse from dth index to the last element
-reverse the the whole array
"""
def rotate_array(arr,d):
#Handle cases where d is larger than the size of the array
d = d%len(arr)
arr = arr[d-1::-1]+arr[:d-1:-1]
return arr[::-1]
"""
given an array, rotate it to the right by d elements.
Solution
-reverse from -dth element to the last element.
-reverse from first element (len(arr)-d)th element
-reverse the the whole array
"""
def rotate_array_right(arr,d):
#Handle cases where d is larger than the size of the array
d = d%len(arr)
n = len(arr)
arr = arr[(n-1)-d::-1]+ arr[:(n-1)-d:-1]
return arr[::-1]