Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Print left rotation of array in O(n) time and O(1) space in C Program.
We are given an array of some size n and multiple integer values, we need to rotate an array from a given index k. Left rotation means moving elements to the left by k positions, where elements that go beyond the beginning wrap around to the end.
We want to rotate an array from an index k like −
Syntax
void leftRotate(int arr[], int n, int k); // arr[] - array to rotate // n - size of array // k - number of positions to rotate left
Algorithm
START
Step 1 -> Declare function void leftRotate(int arr[], int n, int k)
Calculate effective rotation: 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 and initialize
Calculate size of array
Call leftRotate() with different k values
STOP
Example
Here's a complete C program that demonstrates left rotation of an array in O(n) time and O(1) space −
#include <stdio.h>
void leftRotate(int arr[], int n, int k) {
int cal = k % n; // Handle cases where k > n
printf("Left rotation by %d positions: ", k);
for (int i = 0; i < n; i++) {
printf("%d ", arr[(cal + i) % n]);
}
printf("<br>");
}
int main() {
int a[] = {1, 2, 3, 4, 5};
int size = sizeof(a) / sizeof(a[0]);
printf("Original array: ");
for (int i = 0; i < size; i++) {
printf("%d ", a[i]);
}
printf("<br><br>");
// Test with different rotation values
leftRotate(a, size, 1);
leftRotate(a, size, 2);
leftRotate(a, size, 3);
leftRotate(a, size, 6); // k > array size
return 0;
}
Output
Original array: 1 2 3 4 5 Left rotation by 1 positions: 2 3 4 5 1 Left rotation by 2 positions: 3 4 5 1 2 Left rotation by 3 positions: 4 5 1 2 3 Left rotation by 6 positions: 2 3 4 5 1
How It Works
The algorithm uses modular arithmetic to achieve O(1) space complexity:
-
Step 1: Calculate
cal = k % nto handle rotations greater than array size -
Step 2: For each position i, print element at index
(cal + i) % n - Time Complexity: O(n) for printing all elements
- Space Complexity: O(1) as no extra array is used
Key Points
- Using
k % nensures that rotations beyond array size work correctly - The formula
(cal + i) % nwraps around when index exceeds array bounds - This approach only prints the rotated view without modifying the original array
Conclusion
This left rotation technique efficiently displays the rotated array using modular arithmetic in O(n) time and O(1) space. It handles all edge cases including rotations larger than the array size.
Advertisements
