Left rotation of an array using vectors in C++
Last Updated :
01 Jun, 2022
Given an array arr[] of integers and another integer D, the task is to perform D left rotations on the array and print the modified array.
Examples:
Input: arr[] = {1, 2, 3, 4, 5, 6}, D = 2
Output: 3 4 5 6 1 2
Input: arr[] = {1, 2, 3, 4, 5, 6}, D = 12
Output: 1 2 3 4 5 6
Approach: Using vectors in C++, a rotation can be performed by removing the first element from the vector and then inserting it in the end of the same vector. Similarly, all the required rotations can be performed and then print the contents of the modified vector to get the required rotated array.
Below is the implementation of the above approach:
CPP
#include <bits/stdc++.h>
using namespace std;
void rotate(vector< int >& vec, int d)
{
if (d == 0)
return ;
for ( int i = 0; i < d; i++)
{
vec.push_back(vec[0]);
vec.erase(vec.begin());
}
for ( int i = 0; i < vec.size(); i++)
{
cout << vec[i] << " " ;
}
}
int main()
{
vector< int > vec = { 1, 2, 3, 4, 5, 6 };
int n = vec.size();
int d = 2;
rotate(vec, d % n);
return 0;
}
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...