Description: Given an array of size ‘n’, we have to rotate the array by ‘k’ elements in the anti-clock direction.

 
If video does not load, Click here
 
Example:
Input:
 
3  4   5   6   7   8 and k=2
Output:
5  6   7    8   3   4
 
Algorithm:

1)Reverse the arr[0..k-1].

2)Reverse the arr[k..n-1]

3)Reverse the entire arr[0..n-1] 

Implementation using C:

/*The function rotates array by 'k' elements*/

void rotate(int arr[], int k, int n)

{

  reverse(arr, 0, k-1);

  reverse(arr, k, n-1);

  reverse(arr, 0, n-1);

}

/*The following function reverses array elements from index 'i' to 'j'*/.

void reverse(int arr[], int i, int j)

{

  int temp;

  while(j>i)

  {

    temp = arr[j];

    arr[j] = arr[i];

    arr[i] = temp;

    j--;

    i++; 

  }

}

Time Complexity:

O(n)

Auxiliary Space:

O(1)

Go to top