Left Rotate Array by K Positions

Code

#include <stdio.h>

void reverse(int start, int end, int arr[])
{
    // two pointers reversal
	while (start < end) {
        int temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;
        start++;
        end--;
    }
}

void rotate_left(int arr[], int n, int k)
{
	/* One of the simple O(n) operations for arrays is reversal.
    * In a left-rotation, some k elements will be placed on the other
    * side of the array, while n - k elements will also be on their opposite side.
    * You can do a single full reversal to put all elements on the side of
    * the array they are supposed to be on. And then do two more individual
    * reversals to retain the correct ordering of elements.
	*/
    k = k % n;
	reverse(0, n - 1, arr);
	reverse(0, n - k  - 1,  arr);
	reverse(n - k, n - 1, arr);
}

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;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

5 2 1 2 3 4 5

Expected Output

3 4 5 1 2