From e81e2f84097fe1b2a929cf64026bf6d29d603993 Mon Sep 17 00:00:00 2001 From: Sankalp Sharma Date: Mon, 17 May 2021 11:44:23 +0530 Subject: [PATCH] rotate array complete --- algorithms/Python/arrays/rotate_array.py | 26 ++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 algorithms/Python/arrays/rotate_array.py diff --git a/algorithms/Python/arrays/rotate_array.py b/algorithms/Python/arrays/rotate_array.py new file mode 100644 index 00000000..f4a621de --- /dev/null +++ b/algorithms/Python/arrays/rotate_array.py @@ -0,0 +1,26 @@ +""" +Algorithm Type: Array Traversal +Time Complexity: O(n) +""" +numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] +k = 3 + +def rotate_array(numbers, k): + n = len(numbers) + k = k % n + if k == 0: + return numbers + for i in range(n-k): + if i>((n-k)//2): + break + numbers[i], numbers[n-k-(i+1)] = numbers[n-k-(i+1)], numbers[i] + + for i in range(k): + if i>k//2: + break + numbers[-1-i], numbers[-k+i] = numbers[-k+i], numbers[-1-i] + reversed_numbers = numbers[::-1] + return reversed_numbers + +if __name__ == "__main__": + print(rotate_array(numbers, k))