Python Program for array rotation

Python Program for array rotation

Array rotation is a common problem where the task is to rotate an array to the left or right by a certain number of positions. Let's see how we can perform left rotation. Right rotation is just a small tweak on the same idea.

1. Using Temporary Array:

One of the simplest ways to rotate an array is to use a temporary array.

def rotate_left(arr, d): n = len(arr) temp = arr[:d] for i in range(n-d): arr[i] = arr[i+d] arr[n-d:] = temp return arr # Test arr = [1, 2, 3, 4, 5, 6, 7] d = 2 print(rotate_left(arr, d)) 

2. Using the Reverse Algorithm:

Another approach to rotate the array without using extra space is the reverse algorithm.

Steps:

  1. Reverse the sub-array A[0...d-1].
  2. Reverse the sub-array A[d...n-1].
  3. Reverse the entire array A[0...n-1].
def reverse_array(arr, start, end): while start < end: arr[start], arr[end] = arr[end], arr[start] start += 1 end -= 1 def rotate_left(arr, d): n = len(arr) reverse_array(arr, 0, d-1) reverse_array(arr, d, n-1) reverse_array(arr, 0, n-1) return arr # Test arr = [1, 2, 3, 4, 5, 6, 7] d = 2 print(rotate_left(arr, d)) 

3. One by One Rotation:

Rotate the elements one by one.

def left_rotate_by_one(arr): temp = arr[0] for i in range(len(arr)-1): arr[i] = arr[i+1] arr[-1] = temp def rotate_left(arr, d): for _ in range(d): left_rotate_by_one(arr) return arr # Test arr = [1, 2, 3, 4, 5, 6, 7] d = 2 print(rotate_left(arr, d)) 

Among the above methods:

  • The first method is the most intuitive but uses extra space.
  • The second method (reversal) is efficient and uses O(1) space.
  • The third method is the least efficient with O(n*d) time complexity but provides another perspective on the problem.

More Tags

readonly-attribute selection fuzzy-search ip-address uitableviewrowaction nsnumberformatter web3js dynamically-generated default-constructor mediawiki-api

More Programming Guides

Other Guides

More Programming Examples