#include <iostream>
using namespace std;
void rotateByOne(int arr[], int n)
{
int x = arr[0];
for (int y = 0; y < n - 1; y++)
{
arr[y] = arr[y + 1];
}
arr[n - 1] = x;
}
int main()
{
int n, d;
cin >> n >> d;
int arr[n];
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
while (d != 0)
{
rotateByOne(arr, n);
d--;
}
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
return 0;
}
How Do i Reduce the compile time of this code which is written to take an array input of n integers and rotate array left by d times....... I found this on hacker rank and geeksforgeeks, Iam getting correct output from this code but the problem is time.
If the goal is simply to write the rotated array, you don't need to modify the array or to create another one.
Note: using two loops instead of one allows to avoid the use of the modulo operation.
#include <iostream>
#include <vector>
int main() {
std::vector<int> arr = {0, 1, 2, 3, 4, 5, 6, 7};
int n = arr.size();
int d = 3;
for (int i = d; i < n; ++i) {
std::cout << arr[i] << " ";
}
for (int i = 0; i < d; ++i) {
std::cout << arr[i] << " ";
}
std::cout << "\n";
return 0;
}