Open In App

Python Program for Reversal algorithm for array rotation

Last Updated : 26 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Write a function rotate(arr[], d, n) that rotates arr[] of size n by d elements. In this article, we will explore the Reversal Algorithm for array rotation and implement it in Python.

Example

Input:  arr[] = [1, 2, 3, 4, 5, 6, 7]
         d = 2
Output: arr[] = [3, 4, 5, 6, 7, 1, 2] 
Array

Rotation of the above array by 2 will make an array

ArrayRotation1

Python Program for Reversal Algorithm of Array Rotation

Python3
# Function to reverse arr[]
def rverseArray(arr,d):
    c=(arr[d:])+(arr[:d])
    return c
# Driver function to test above functions
arr = [1, 2, 3, 4, 5, 6, 7]
d=2
print(rverseArray(arr,d))

Output
[3, 4, 5, 6, 7, 1, 2]

Python Program for Reversal algorithm for Array Rotation

Python3
# Python program for reversal algorithm of array rotation
 
# Function to reverse arr[] from index start to end
def rverseArray(arr, start, end):
    while (start < end):
        temp = arr[start]
        arr[start] = arr[end]
        arr[end] = temp
        start += 1
        end = end-1

# Function to left rotate arr[] of size n by d
def leftRotate(arr, d):
    n = len(arr)
    rverseArray(arr, 0, d-1)
    rverseArray(arr, d, n-1)
    rverseArray(arr, 0, n-1)
 # Function to print an array
def printArray(arr):
    for i in range(0, len(arr)):
        print (arr[i])
 # Driver function to test above functions
arr = [1, 2, 3, 4, 5, 6, 7]
leftRotate(arr, 2) # Rotate array by 2
printArray(arr)
 

Output
3
4
5
6
7
1
2

Python Program for Reversal Algorithm Using collections.deque

Python3
from collections import deque

def rotate_array_deque(arr, d):
    n = len(arr)
    rotated_array = deque(arr)
    rotated_array.rotate(-d)
    return list(rotated_array)

# Example
arr = [1, 2, 3, 4, 5, 6, 7]
d = 2

rotated_array = rotate_array_deque(arr, d)
print("Rotated array:", rotated_array)

Output
Rotated array: [3, 4, 5, 6, 7, 1, 2]

Time complexity: O(n + k).
Auxiliary space: O(n)


Next Article
Article Tags :
Practice Tags :

Similar Reads

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy