Skip to content

Instantly share code, notes, and snippets.

@jishnujayakumar
Created February 26, 2021 12:42
Show Gist options
  • Save jishnujayakumar/b6d9acf5aca2ef48812837aef8d8e363 to your computer and use it in GitHub Desktop.
Save jishnujayakumar/b6d9acf5aca2ef48812837aef8d8e363 to your computer and use it in GitHub Desktop.
Naive in-place array rotation
def rotate_array(arr, k):
element_at_secondary_index = None
primary_index = 0
steps = 0
n = len(arr)
while steps < n:
secondary_index = (primary_index+k) % n
if element_at_secondary_index is None:
element_at_secondary_index, arr[secondary_index] = arr[secondary_index], arr[primary_index]
else:
temp = arr[secondary_index]
arr[secondary_index], element_at_secondary_index = element_at_secondary_index, temp
primary_index = secondary_index
steps +=1
return arr
# Test
print(rotate_array(arr=[1,2,3,4,5,6,7], k=3))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment