#include <stdio.h>
#include <stdint.h>
void rotate_left(int arr[], int n, int k)
{
uint8_t step_count = k % n;
if (step_count == 0)
{
return;
}
int temp[100] = {0};
uint8_t index = 0;
for ( ; index < step_count; index++)
{
temp[index] = arr[index];
}
for ( ; index < n; index++)
{
arr[index - step_count] = arr[index];
}
for ( ; index < (n + step_count); index++)
{
arr[index - step_count] = temp[index - n];
}
}
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;
}This C program performs a left rotation on an array by $k$ positions. Rotating an array to the left means shifting all elements toward the beginning of the array, and the elements that "fall off" the front are moved to the back.
The function rotate_left uses a temporary buffer to hold the elements that will be moved to the end of the array.
1. Optimization: The Modulo Operator
uint8_t step_count = k % n;
If you rotate an array of size 5 by 5 positions, it ends up exactly where it started. By using the modulo operator, the code ensures that if $k$ is larger than $n$, we only perform the necessary number of shifts (e.g., rotating by 12 on a 10-element array is the same as rotating by 2).
2. Phase 1: Store the "Lost" Elements
The first step_count elements (the ones that will be pushed out of the front) are copied into a temporary array temp.
3. Phase 2: Shift Remaining Elements Left
The loop for ( ; index < n; index++) moves the rest of the elements in the original array forward to fill the gaps left by the elements we just saved.
4. Phase 3: Move Saved Elements to the Back
The final loop takes the elements from temp and places them at the end of the original array, completing the rotation.
Input
5 2 1 2 3 4 5
Expected Output
3 4 5 1 2