Home > Backend Development > C++ > 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
Release: 2023-09-10 15:45:07
forward
633 people have browsed it

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
Copy after login

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
Copy after login

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;
}
Copy after login

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
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template