#include <stdio.h>
void helper_fun(int *a,int n)
{
int i;
int temp;
for(i=0;i<n/2;i++)
{
temp=a[i];
a[i]=a[n-i-1];
a[n-i-1]=temp;
}
}
void rotate_left(int a[], int n, int k)
{
if(k>n) //This conditions is required for edge cases
k=k-n;
helper_fun(a,k); //Step-1:first reverse the array corresponding to first k elements.
helper_fun(a+k,n-k); //Step-2:next reverse the array corresponding to last n-k elements.
helper_fun(a,n); //Step-3:now, perform reverse array on entire array.
//For Right rotate,all steps are same. We need to call helper function of step-3 in step-1 and then implement the helper mentioned in step-1 and step-2 previously.
}
int main() {
int n, k;
scanf("%d %d", &n, &k);
int arr[100];
// Read array elements
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Rotate the array
rotate_left(arr, n, k);
// Print the rotated array
for (int i = 0; i < n; i++) {
printf("%d", arr[i]);
if(i < n-1){
printf(" ");
}
}
return 0;
}
Input
5 2 1 2 3 4 5
Expected Output
3 4 5 1 2