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 −

Array Left Rotation by k=2 Original Array: 1 2 3 4 5 0 1 2 3 4 Rotate left by 2 After Rotation: 3 4 5 1 2

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 % n to 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 % n ensures that rotations beyond array size work correctly
  • The formula (cal + i) % n wraps 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.

Updated on: 2026-03-15T11:52:00+05:30

243 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements