The naïve approach to solve this problem is to shift the all elements d times but this is a time-consuming process.
We can use a small trick here to print the elements of the array after left rotating d elements.
Let,
i = ith iteration
D = number of elements to rotate
N = size of array
Then to left rotate array we can use -
arr[i] = arr[(i+D)%N]
C++ Implementation:
#include <iostream>
using namespace std;
int main()
{
int n,d;
//input value of n and d
cout<<"Enter the value of n and d"<<endl;
cin>>n>>d;
int a[n];
//input array elements
cout<<"enter the array elements : ";
for(int i=0;i<n;i++)
{
cin>>a[i];
}
//print the elements of array after rotation
cout<<"array elements after rotation : ";
for(int i=0;i<n;i++)
{
cout<<a[(i+d)%n]<<" ";
}
return 0;
}
Output
Enter the value of n and d
7 3
enter the array elements : 1 2 3 4 5 6 7
array elements after rotation : 4 5 6 7 1 2 3
The naïve approach to solve this problem is to shift the all elements d times but this is a time-consuming process.
We can use a small trick here to print the elements of the array after left rotating d elements.
Let, i = ith iteration D = number of elements to rotate N = size of array Then to left rotate array we can use - arr[i] = arr[(i+D)%N]C++ Implementation:
Output