All submissions

Left Rotate Array by K Positions

Code

#include <stdio.h>

// void rotate_left(int arr[], int n, int k) { 
//     int original = 0; 
//     for (int i = 0; i < k; i ++) { 
//         for (int x = 0; x < n; x++){ // before any shifting int index = x - 1; 
//             if (index <= 0){ // put it to the max index = n - 1; 
//             original = arr[index]; 
//             arr[index] = original; 
//             } 
//         original = arr[x]; 
//         arr[index] = original; } 
//             } 
//         }


void rotate_left(int arr[], int n, int k) {
    int original = 0; 
    for (int i = 0; i < k; i++) { 
        // save the first element before shifting
        original = arr[0];

        // shift everything one step left
        for (int x = 0; x < n - 1; x++) { 
            arr[x] = arr[x + 1];
        }
        // put saved element at the end
        arr[n - 1] = original;
    }
}

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

 

 

 

Loading...

Input

5 2 1 2 3 4 5

Expected Output

3 4 5 1 2