Rotate an array by given number of positions

Given an array, the task is to rotate the given array.
Array rotation is the process of shifting the elements of an array by a specified number of positions. 
In a left rotation, the elements of the array are shifted to the left by a certain number of positions, and the elements that are shifted out of the array from the left are placed back at the end. Similarly, in a right rotation, the elements are shifted to the right, and the elements that are shifted out from the right are placed back at the beginning.

How Array Rotation Works ?

There are two types of rotations:

  • Left Rotation: Shift elements to the left by a specified number of positions.
  • Right Rotation: Shift elements to the right by a specified number of positions.

Left Rotation Example:

For an array [1, 2, 3, 4, 5] and a left rotation by 2 positions, the array becomes [3, 4, 5, 1, 2].

Right Rotation Example:

For an array [1, 2, 3, 4, 5] and a right rotation by 2 positions, the array becomes [4, 5, 1, 2, 3].

Algorithm for Array Rotation

There are multiple ways to rotate an array, but a simple and efficient way is to use array slicing. Below, we will use this method for both left and right rotations.

Step-by-step explanation:

  1. Left Rotation:
    • Shift elements from the start of the array to the end.
    • The first d elements of the array are moved to the end.
    • The remaining elements are moved to the beginning.
  2. Right Rotation:
    • Shift elements from the end of the array to the start.
    • The last d elements of the array are moved to the front.
    • The remaining elements are moved to the end.

C++ Program to Rotate an array

cpp
#include <iostream>
using namespace std;

// Function to left rotate an array by d positions
void leftRotate(int arr[], int n, int d) {
    d = d % n;  // Handle case when d > n
    int temp[d];  // Temporary array to store first d elements

    // Store first d elements in a temporary array
    for (int i = 0; i < d; i++) {
        temp[i] = arr[i];
    }

    // Shift the rest of the elements to the left
    for (int i = 0; i < n - d; i++) {
        arr[i] = arr[i + d];
    }

    // Place the stored elements at the end
    for (int i = 0; i < d; i++) {
        arr[n - d + i] = temp[i];
    }
}

// Function to right rotate an array by d positions
void rightRotate(int arr[], int n, int d) {
    d = d % n;  // Handle case when d > n
    int temp[d];  // Temporary array to store last d elements

    // Store last d elements in a temporary array
    for (int i = 0; i < d; i++) {
        temp[i] = arr[n - d + i];
    }

    // Shift the rest of the elements to the right
    for (int i = n - 1; i >= d; i--) {
        arr[i] = arr[i - d];
    }

    // Place the stored elements at the beginning
    for (int i = 0; i < d; i++) {
        arr[i] = temp[i];
    }
}

// Function to print the array
void printArray(int arr[], int n) {
    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
}

// Main function
int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int n = sizeof(arr) / sizeof(arr[0]);

    cout << "Original array: ";
    printArray(arr, n);

    leftRotate(arr, n, 2);
    cout << "Left rotated array by 2 positions: ";
    printArray(arr, n);

    rightRotate(arr, n, 2);
    cout << "Right rotated array by 2 positions: ";
    printArray(arr, n);

    return 0;
}

Java Program to Rotate an array

java
public class Main {
    // Function to left rotate an array by d positions
    public static void leftRotate(int arr[], int d) {
        int n = arr.length;
        d = d % n;  // Handle case when d > n
        int[] temp = new int[d];  // Temporary array to store first d elements

        // Store first d elements in a temporary array
        for (int i = 0; i < d; i++) {
            temp[i] = arr[i];
        }

        // Shift the rest of the elements to the left
        for (int i = 0; i < n - d; i++) {
            arr[i] = arr[i + d];
        }

        // Place the stored elements at the end
        for (int i = 0; i < d; i++) {
            arr[n - d + i] = temp[i];
        }
    }

    // Function to right rotate an array by d positions
    public static void rightRotate(int arr[], int d) {
        int n = arr.length;
        d = d % n;  // Handle case when d > n
        int[] temp = new int[d];  // Temporary array to store last d elements

        // Store last d elements in a temporary array
        for (int i = 0; i < d; i++) {
            temp[i] = arr[n - d + i];
        }

        // Shift the rest of the elements to the right
        for (int i = n - 1; i >= d; i--) {
            arr[i] = arr[i - d];
        }

        // Place the stored elements at the beginning
        for (int i = 0; i < d; i++) {
            arr[i] = temp[i];
        }
    }

    // Function to print the array
    public static void printArray(int arr[]) {
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
    }

    // Main function
    public static void main(String[] args) {
        int arr[] = {1, 2, 3, 4, 5};

        System.out.println("Original array:");
        printArray(arr);

        leftRotate(arr, 2);
        System.out.println("Left rotated array by 2 positions:");
        printArray(arr);

        rightRotate(arr, 2);
        System.out.println("Right rotated array by 2 positions:");
        printArray(arr);
    }
}

Python Program to Rotate an array

python
# Function to left rotate an array by d positions
def left_rotate(arr, d):
    n = len(arr)
    d = d % n  # Handle case when d > n
    arr[:] = arr[d:] + arr[:d]  # Slice and concatenate the array

# Function to right rotate an array by d positions
def right_rotate(arr, d):
    n = len(arr)
    d = d % n  # Handle case when d > n
    arr[:] = arr[-d:] + arr[:-d]  # Slice and concatenate the array

# Function to print the array
def print_array(arr):
    print(" ".join(map(str, arr)))

# Main function
if __name__ == "__main__":
    arr = [1, 2, 3, 4, 5]

    print("Original array:")
    print_array(arr)

    left_rotate(arr, 2)
    print("Left rotated array by 2 positions:")
    print_array(arr)

    right_rotate(arr, 2)
    print("Right rotated array by 2 positions:")
    print_array(arr)

DSA

8604

307

Related Articles