Open In App

C++ Program to Print all possible rotations of a given Array

Last Updated : 19 May, 2023
Comments
Improve
Suggest changes
2 Likes
Like
Report

Given an integer array arr[] of size N, the task is to print all possible rotations of the array.
Examples: 

Input: arr[] = {1, 2, 3, 4} 
Output: {1, 2, 3, 4}, {4, 1, 2, 3}, {3, 4, 1, 2}, {2, 3, 4, 1} 
Explanation: 
Initial arr[] = {1, 2, 3, 4} 
After first rotation arr[] = {4, 1, 2, 3} 
After second rotation arr[] = {3, 4, 1, 2} 
After third rotation arr[] = {2, 3, 4, 1} 
After fourth rotation, arr[] returns to its original form.
Input: arr[] = [1] 
Output: [1] 

Approach 1: 
Follow the steps below to solve the problem:  

  1. Generate all possible rotations of the array, by performing a left rotation of the array one by one.
  2. Print all possible rotations of the array until the same rotation of array is encountered.

Below is the implementation of the above approach : 


Output: 
[1, 2, 3, 4] [4, 1, 2, 3] [2, 3, 4, 1] [3, 4, 1, 2]

 

Time Complexity: O (N2
Auxiliary Space: O (1)

Approach 2: Follow the steps below to solve the problem:  

  1. Declare an array arr and initialize it with some values. Find the length of the array n.
  2. Create a new array rotatedArr of twice the length of the input array. Copy the elements of the input array twice into the rotatedArr, first in the first half of the array and then in the second half of the array.
  3. Iterate over the indices from 0 to n and generate all possible rotations of the array. For each index i, print a sub-array of rotatedArr starting from index i and having length n.

Output
[1 2 3 4] [2 3 4 1] [3 4 1 2] [4 1 2 3] 

Time Complexity: O(n2
Space Complexity: O(n)

Please refer complete article on Print all possible rotations of a given Array for more details!
 


Next Article
Practice Tags :

Similar Reads