Created
December 25, 2022 07:41
-
-
Save ronzhin-dmitry/03816b3bfa7acc773b970f94dfbb1a1a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def rotate_with_reflections(arr,k): #inputs are array and number of steps to move k | |
n = len(arr) | |
for i in range(n//2): #make the first reflection - line from the first element of the array | |
buf = arr[i] #additional memory O(1) | |
arr[i] = arr[n-1-i] | |
arr[n-1-i] = buf | |
for i in range(k//2): #second reflection is made by parts to ease up code: | |
buf = arr[i] #additional memory O(1) | |
arr[i] = arr[k-1-i] | |
arr[k-1-i] = buf | |
for i in range((n-k)//2): | |
buf = arr[k+i] #additional memory O(1) | |
arr[k+i] = arr[n-1-i] | |
arr[n-1-i] = buf | |
#total additional memory is O(1) | |
#time complexity is O(n) since every element is traversed no more than two times | |
return arr | |
print(rotate_with_reflections(list(range(10)),3)) | |
#Output: [7, 8, 9, 0, 1, 2, 3, 4, 5, 6] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment