Skip to content

Instantly share code, notes, and snippets.

@ronzhin-dmitry
Created December 25, 2022 07:16
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/af0856b905a5d4724fce0c21db09b727 to your computer and use it in GitHub Desktop.
Save ronzhin-dmitry/af0856b905a5d4724fce0c21db09b727 to your computer and use it in GitHub Desktop.
def rotate_slow_cheap(arr, k): #inputs are array and the number of steps to rotate to the right k
n = len(arr)
for i in range(k): #k times repeat 1-step rotation
last_element = arr[-1] #the only additional memory - О(1)
for j in range(n-1,0,-1):#move the values, traversing from the end of the array
arr[j] = arr[j-1]
arr[0] = last_element
#time complexity is O(n*k)
return arr
print(rotate_slow_cheap(list(range(10)),3))
#Output: [7, 8, 9, 0, 1, 2, 3, 4, 5, 6]
def rotate_fast_expensive(arr, k): #inputs are array and the number of steps to rotate to the right k
n = len(arr)
saved_slice = arr[n-k:][:] #copy of the end of the array - O(k)
for i in range(n-1, k-1, -1): #move elements k steps to the right
arr[i] = arr[(i-k)%n]
for i in range(k):
arr[i] = saved_slice[i]
#time complexity O(n)
return arr
print(rotate_fast_expensive(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