Created
December 25, 2022 07:48
-
-
Save ronzhin-dmitry/872b1076d8c29e83a7c22c0b9fe2f90b 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_cycles(arr,k): #inputs are array and number of steps to rotate k | |
if k == 0: | |
return arr #corner case | |
n = len(arr) | |
moved_counter = 0 #additional memory (total O(1)) | |
cur_start = 0 | |
pointer = k | |
prev_element = arr[0] | |
while moved_counter <n: | |
buf = arr[pointer] #one more variable O(1) memory | |
arr[pointer] = prev_element | |
prev_element = buf | |
moved_counter += 1 | |
if pointer == cur_start: #if we meet a cycle we possibly need to move to the right once | |
cur_start += 1 | |
pointer = cur_start | |
prev_element = arr[cur_start] | |
pointer = (pointer + k) % n | |
#total memory O(1) | |
#time complexity O(n) since we traverse each element no more than once | |
return arr | |
print(rotate_with_cycles(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