0
0
JavaProgramBeginner · 2 min read

Java Program to Rotate Array with Output and Explanation

To rotate an array in Java, use a method that shifts elements by k positions using a temporary array or reverse parts of the array; for example, rotate(int[] arr, int k) shifts elements right by k places.
📋

Examples

Inputarr = [1, 2, 3, 4, 5], k = 2
Output[4, 5, 1, 2, 3]
Inputarr = [10, 20, 30, 40], k = 1
Output[40, 10, 20, 30]
Inputarr = [7, 8, 9], k = 3
Output[7, 8, 9]
🧠

How to Think About It

To rotate an array by k positions, think of moving the last k elements to the front and shifting the rest to the right. You can do this by temporarily saving the last k elements, shifting the others right, then placing the saved elements at the start. This keeps the order and rotates the array as needed.
📐

Algorithm

1
Get the array and the number k of positions to rotate.
2
Adjust k if it is larger than the array length by using k modulo array length.
3
Create a temporary array to store the last k elements.
4
Shift the elements of the original array to the right by k positions.
5
Copy the saved elements from the temporary array to the start of the original array.
6
Return or print the rotated array.
💻

Code

java
public class RotateArray {
    public static void rotate(int[] arr, int k) {
        int n = arr.length;
        k = k % n;
        int[] temp = new int[k];
        for (int i = 0; i < k; i++) {
            temp[i] = arr[n - k + i];
        }
        for (int i = n - 1; i >= k; i--) {
            arr[i] = arr[i - k];
        }
        for (int i = 0; i < k; i++) {
            arr[i] = temp[i];
        }
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        int k = 2;
        rotate(arr, k);
        for (int num : arr) {
            System.out.print(num + " ");
        }
    }
}
Output
4 5 1 2 3
🔍

Dry Run

Let's trace rotating the array [1, 2, 3, 4, 5] by 2 positions.

1

Calculate effective rotation

k = 2 % 5 = 2

2

Save last k elements

temp = [4, 5]

3

Shift elements right by k

arr becomes [1, 2, 3, 3, 4]

4

Copy saved elements to front

arr becomes [4, 5, 1, 2, 3]

IterationArray State
Initial[1, 2, 3, 4, 5]
Save last 2temp = [4, 5]
Shift right[1, 2, 3, 3, 4]
Copy temp front[4, 5, 1, 2, 3]
💡

Why This Works

Step 1: Calculate k modulo array length

Using k % n ensures rotation does not exceed array size and handles cases where k is larger than the array.

Step 2: Save last k elements

We temporarily store the last k elements to avoid overwriting them during shifting.

Step 3: Shift elements right

Elements before the last k are moved right by k positions to make space at the front.

Step 4: Place saved elements at front

Finally, the saved elements are copied to the start, completing the rotation.

🔄

Alternative Approaches

Using array reversal
java
public class RotateArray {
    public static void reverse(int[] arr, int start, int end) {
        while (start < end) {
            int temp = arr[start];
            arr[start] = arr[end];
            arr[end] = temp;
            start++;
            end--;
        }
    }

    public static void rotate(int[] arr, int k) {
        int n = arr.length;
        k = k % n;
        reverse(arr, 0, n - 1);
        reverse(arr, 0, k - 1);
        reverse(arr, k, n - 1);
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        int k = 2;
        rotate(arr, k);
        for (int num : arr) {
            System.out.print(num + " ");
        }
    }
}
This method uses three reversals to rotate in-place without extra space, making it efficient but slightly more complex to understand.
Using a new array for rotation
java
public class RotateArray {
    public static int[] rotate(int[] arr, int k) {
        int n = arr.length;
        k = k % n;
        int[] rotated = new int[n];
        for (int i = 0; i < n; i++) {
            rotated[(i + k) % n] = arr[i];
        }
        return rotated;
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        int k = 2;
        int[] result = rotate(arr, k);
        for (int num : result) {
            System.out.print(num + " ");
        }
    }
}
This approach is simple and easy to understand but uses extra memory equal to the array size.

Complexity: O(n) time, O(k) or O(1) depending on method space

Time Complexity

The rotation requires moving each element once, so it takes O(n) time where n is the array length.

Space Complexity

Using a temporary array for k elements uses O(k) space; the reversal method uses O(1) extra space.

Which Approach is Fastest?

All methods run in O(n) time, but the reversal method is fastest in space as it rotates in-place without extra arrays.

ApproachTimeSpaceBest For
Temporary arrayO(n)O(k)Simple and clear for small k
Array reversalO(n)O(1)In-place rotation with minimal space
New arrayO(n)O(n)Easy to understand but uses extra memory
💡
Always use k modulo array length to handle rotations larger than the array size.
⚠️
Forgetting to adjust k with modulo causes incorrect rotations or errors when k is larger than the array length.