Created
February 26, 2021 12:42
-
-
Save jishnujayakumar/b6d9acf5aca2ef48812837aef8d8e363 to your computer and use it in GitHub Desktop.
Naive in-place array rotation
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_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