Given an array, cyclically rotate the array clockwise by one. Examples:
Input: arr = [1, 2, 3, 4, 5] Output: arr = [5, 1, 2, 3, 4]
We have existing solution for this problem please refer Program to cyclically rotate an array by one link. We will solve this problem in python quickly using List Comprehension. Approach is very simple, just remove last element in list and append it in front of remaining list.
Python3
# Program to cyclically rotate an array by one def cyclicRotate( input ): # slice list in two parts and append # last element in front of the sliced list # [input[-1]] --> converts last element pf array into list # to append in front of sliced list # input[0:-1] --> list of elements except last element print ([ input [ - 1 ]] + input [ 0 : - 1 ]) # Driver program if __name__ = = "__main__": input = [ 1 , 2 , 3 , 4 , 5 ] cyclicRotate( input ) |
Output:
[5, 1, 2, 3, 4]
Time Complexity: O(n)
Auxiliary Space: O(1)
Approach#2: Using temporary variable
This approach uses a for loop and temporary variable to cyclically rotate the given array by one position.
Algorithm
1. Store the last element of the array in a temporary variable.
2. Shift each element one position to the right using a for loop.
3. Move the temporary variable to the first position of the array.
4. Print the rotated array.
Python3
arr = [ 1 , 2 , 3 , 4 , 5 ] n = len (arr) # store last element in a temporary variable temp = arr[n - 1 ] # shift each element one position to the right for i in range (n - 1 , 0 , - 1 ): arr[i] = arr[i - 1 ] # move the temporary variable to the first position arr[ 0 ] = temp print (arr) |
[5, 1, 2, 3, 4]
Time Complexity: The for loop runs from n-1 to 0, which takes O(n) time. Therefore, the time complexity of this code is O(n).
Space Complexity: The code uses a temporary variable to store the last element of the array, which takes O(1) space. Therefore, the space complexity of this code is O(1).