# Left rotation of an array using vectors in C++

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

 `// C++ implementation of the approach` `#include ` `using` `namespace` `std;`   `// Function to left rotate the array by d elements` `// here we are passing vector by reference to avoid copying` `// that just make our program slow` `void` `rotate(vector<``int``>& vec, ``int` `d)` `{` `    ``// Base case` `    ``if` `(d == 0)` `        ``return``;`   `    ``// Push first d elements from the beginning` `    ``// to the end and remove those elements` `    ``// from the beginning` `    ``for` `(``int` `i = 0; i < d; i++)` `    ``{` `        ``// adding first element at` `        ``// the end of vector` `        ``vec.push_back(vec[0]); ` `      `  `        ``// removing first element` `        ``vec.erase(vec.begin()); ` `    ``}`   `    ``// Print the rotated array` `    ``for` `(``int` `i = 0; i < vec.size(); i++) ` `    ``{` `        ``cout << vec[i] << ``" "``;` `    ``}` `}`   `// Driver code` `int` `main()` `{` `    ``vector<``int``> vec = { 1, 2, 3, 4, 5, 6 };` `    ``int` `n = vec.size();` `    ``int` `d = 2;`   `    ``// Function call` `    ``rotate(vec, d % n);`   `    ``return` `0;` `}`

Output

`3 4 5 6 1 2 `

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

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!

Previous
Next