Left rotate an array by D places in Python

In this post, we will discuss some methods to left rotate an array by D places in Python.

Left rotate an array by D places in Python

You are given an array and value of D (number of places by which the array is to left rotated).

Input: arr=[2,9,4,55,64,3,1]    D=2

Output: [4,55,64,3,1,2,9]

Method-1:

In this method, we take a temporary array in which we take the D number of elements from arr from starting and store it in this temporary array. Then we left shift the rest of the elements by D places in arr and then copy back the elements of temp array to arr.

#Function to populate temp array
def fillTemp(arr, D, n):
    temp=[]
    for i in range(D):
      temp.append(arr[i])
    leftRot(arr,D,n,temp)

#Function to rotate array by D places 
def leftRot(arr,D,n,temp):
    for i in range(n-D):
        arr[i]=arr[D+i]
    for j in range(D):
        arr[n-D+j]=temp[j]
        
# Driver program 
arr = [2,9,4,55,64,3,1]
size=len(arr)
D=2
fillTemp(arr, D, size) 
#Printing Array
for i in range(size): 
    print ("{}".format(arr[i]),end=" ") 


Output:

4,55,64,3,1,2,9

Time Complexity: O(n)

Space Complexity: O(D)

Method-2:

In this method, we left rotate array by rotating each element one by one. We repeat this process D times. We store the first element of arr in a temp variable and then rotate each element by one place and then place this temp variable value at the last index of arr.

 

#Function to left rotate arr 
def leftRot(arr, D, size): 
  for j in range(D): 
    RotOneByOne(arr, size) 

#Function to left Rotate elements one by one
def RotOneByOne(arr, size): 
  temp = arr[0] 
  for k in range(size-1): 
    arr[k] = arr[k+1] 
  arr[size-1] = temp 
    
# Driver program
arr = [2,9,4,55,64,3,1]
size=len(arr)
D=2
leftRot(arr, D, size)
#Printing Array
for i in range(size):
    print ("{}".format(arr[i]))

Output:

4,55,64,3,1,2,9

Time Complexity: O(n*D)

Space Complexity: O(1)

Leave a Reply

Your email address will not be published. Required fields are marked *