Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Python Program to Split the array and add the first part to the end
Next article icon

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 inPython.

Example

Input:arr[] = [1, 2, 3, 4, 5, 6, 7]         d = 2Output: 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[]defrverseArray(arr,d):c=(arr[d:])+(arr[:d])returnc# Driver function to test above functionsarr=[1,2,3,4,5,6,7]d=2print(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 enddefrverseArray(arr,start,end):while(start<end):temp=arr[start]arr[start]=arr[end]arr[end]=tempstart+=1end=end-1# Function to left rotate arr[] of size n by ddefleftRotate(arr,d):n=len(arr)rverseArray(arr,0,d-1)rverseArray(arr,d,n-1)rverseArray(arr,0,n-1)# Function to print an arraydefprintArray(arr):foriinrange(0,len(arr)):print(arr[i])# Driver function to test above functionsarr=[1,2,3,4,5,6,7]leftRotate(arr,2)# Rotate array by 2printArray(arr)

Output
3456712

Python Program for Reversal Algorithm Using collections.deque

Python3
fromcollectionsimportdequedefrotate_array_deque(arr,d):n=len(arr)rotated_array=deque(arr)rotated_array.rotate(-d)returnlist(rotated_array)# Examplearr=[1,2,3,4,5,6,7]d=2rotated_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)


Improve
Article Tags :
Practice Tags :

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp