Left Rotate an Array by one

Input and Output

I/P: arr[] = {1,2,3,4,5}
O/P: arr[] = {2,3,4,5,1}

Logic

Store first element in a temporary variable. Then move remaining elements to their left by one position. Then put the stored element at last position in array.

Code

#include <iostream>
#include <cmath>
using namespace std;
void lRotateOne(int arr[], int n)
{
int temp = arr[0];
for(int i = 1; i < n; i++)
{
arr[i - 1] = arr[i];
}
arr[n - 1] = temp;
}

int main() {

int arr[] = {1, 2, 3, 4, 5}, n = 5;
cout<<"Before Rotation"<<endl;for(int i = 0; i < n; i++)
{
cout<<arr[i]<<" ";
}
cout<<endl;lRotateOne(arr, n);cout<<"After Rotation"<<endl;for(int i = 0; i < n; i++)
{
cout<<arr[i]<<" ";
}

}

Time Complexity

Time Complexity of the above algorithm is O(n).

--

--