Home  >  Article  >  Backend Development  >  Print left rotation of array in C program with O(n) time complexity and O(1) space complexity

Print left rotation of array in C program with O(n) time complexity and O(1) space complexity

PHPz
PHPzforward
2023-09-10 15:45:07589browse

Given an array of size n and multiple integer values, we need to rotate the array starting from the given index k.

We want to rotate the array starting from index k as shown below- p>

Print left rotation of array in C program with O(n) time complexity and O(1) space complexity

Example

Input: arr[] = {1, 2, 3, 4, 5}
   K1 = 1
   K2 = 3
   K3 = 6
Output:
   2 3 4 5 1
   4 5 1 2 3
   2 3 4 5 1

Algorithm

START
Step 1 -> Declare function void leftRotate(int arr[], int n, int k)
   Declare int cal = k% n
   Loop For int i=0 and i<n and i++
      Print arr[(cal+i)%n]
   End
Step 2 -> In main()
   Declare array a[]={ 1,2,3,4}
   Declare int size=sizeof(a)/sizeof(a[0])
   Declare int k=1
   Call leftRotate(a, size, k)
   Set k=2
   Call leftRotate(a, size, k)
   Set k=3
   leftRotate(a, size, k)
STOP

Example

#include <bits/stdc++.h>
using namespace std;
void leftRotate(int arr[], int n, int k){
   int cal = k % n;
   for (int i = 0; i < n; i++)
      cout << (arr[(cal + i) % n]) << " ";
   cout << "</p><p>";
}
int main(){
   int a[] = { 1,2,3,4};
   int size = sizeof(a) / sizeof(a[0]);
   int k = 1;
   leftRotate(a, size, k);
   k = 2;
   leftRotate(a, size, k);
   k = 3;
   leftRotate(a, size, k);
   return 0;
}

Output

If we run the above program then it will generate the following output

2 3 4 1
3 4 1 2
4 1 2 3

The above is the detailed content of Print left rotation of array in C program with O(n) time complexity and O(1) space complexity. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete