Skip to content

Instantly share code, notes, and snippets.

@ronzhin-dmitry
Created December 25, 2022 07:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ronzhin-dmitry/03816b3bfa7acc773b970f94dfbb1a1a to your computer and use it in GitHub Desktop.
Save ronzhin-dmitry/03816b3bfa7acc773b970f94dfbb1a1a to your computer and use it in GitHub Desktop.
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