Given an array arr[] of integers and another integer D, the task is to perform D circular rotations on the array and print the modified array. Examples:
Input: Arr[] = {1, 2, 3, 4, 5, 6}, D = 2 Output: 5 6 1 2 3 4 Input: Arr[] = {1, 2, 3}, D = 2 Output: 2 3 1
Approach: Using Deque in C++, a rotation can be performed deleting the last element from the deque and inserting it at the beginning of the same deque. Similarly, all the required rotations can be performed and then print the contents of the modified deque to get the required rotated array. If the number of rotations is more than the size of the deque then just take the mod with N, So, D = D%N. Where D is the number of rotations and N is the size of the deque. Below is the implementation of the above approach:
CPP
#include <bits/stdc++.h>
using namespace std;
void rotate(deque<int> deq,
int d, int n)
{
for (int i = 0; i < d; i++) {
int val = deq.back();
deq.pop_back();
deq.push_front(val);
}
for (int i = 0; i < n; i++) {
cout << deq[i] << " ";
}
cout << endl;
}
int main()
{
deque<int> v = { 1, 2, 3, 4, 5, 6, 7 };
int n = v.size();
int d = 5;
rotate(v, d % n, n);
}
|
Time Complexity: O(n)
Auxiliary Space: O(n)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
02 Jun, 2022
Like Article
Save Article