Movatterモバイル変換


[0]ホーム

URL:


Open In App

Array rotation means shifting array elements to the left or right by a given number of positions.

Example:

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

Let's explore different methods for array rotation one by one:

Using reverse() Function

This method implements the Reversal Algorithm using Python’s built-in reverse() function. It divides the array into two parts based on rotation count d, reverses each part and then reverses whole array to get the rotated result.

Python
arr=[1,2,3,4,5,6,7]d=2n=len(arr)# Reverse first d elementsarr[:d]=reversed(arr[:d])# Reverse remaining elementsarr[d:]=reversed(arr[d:])# Reverse entire arrayarr.reverse()print(arr)

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

Explanation:

  • Step 1 reverses the first 2 elements -> [2, 1, 3, 4, 5, 6, 7]
  • Step 2 reverses remaining elements -> [2, 1, 7, 6, 5, 4, 3]
  • Step 3 reverses entire array -> [3, 4, 5, 6, 7, 1, 2]

Using collections.deque

deque from the collections module allows fast appends and pops from both ends. It includes a rotate() method that can efficiently rotate elements left or right.

Python
fromcollectionsimportdequearr=[1,2,3,4,5,6,7]d=2res=deque(arr)res.rotate(-d)print(list(res))

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

Explanation:

  • Convert list to deque for efficient rotation.
  • Rotate left by d using rotate(-d).
  • Convert back to list and print the result.

Using Array Slicing

This method uses Python slicing to directly rearrange parts of the array. It’s concise but creates new lists during slicing, so it’s less memory efficient.

Python
arr=[1,2,3,4,5,6,7]d=2res=arr[d:]+arr[:d]print(res)

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

Using Manual Swap Method

This is the manual form of the reversal algorithm where we swap elements manually using loops.

Python
arr=[1,2,3,4,5,6,7]d=2n=len(arr)# Reverse first partstart,end=0,d-1whilestart<end:arr[start],arr[end]=arr[end],arr[start]start+=1end-=1# Reverse second partstart,end=d,n-1whilestart<end:arr[start],arr[end]=arr[end],arr[start]start+=1end-=1# Reverse full arrayarr.reverse()print(arr)

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

Improve
Improve
Article Tags :

Explore

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