Rotate Array in Java: Solution, Explanation & Practice

Rotate array elements to the right

Problem summary

Write a program that rotates array elements by k positions to the right.

Starter code

public class Main {
    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        int k = 2; // Test case 1
        
        // Rotate right by k positions
        // Print space-separated
    }
}

Expected output and test cases

  • Rotate right by 2
    4 5 1 2 3
  • Rotate right by 1
    5 1 2 3 4
  • Rotate by 5 (full circle)
    1 2 3 4 5

Hints

  1. k % length handles k > length
  2. Reverse entire array, then reverse parts
  3. Or use extra array for simpler solution

Validated solution

Reveal Java solution
public class Main {
    static void reverse(int[] values, int left, int right) {
        while (left < right) {
            int temp = values[left]; values[left++] = values[right]; values[right--] = temp;
        }
    }
    static void rotateRight(int[] values, int k) {
        if (values.length == 0) return;
        k = ((k % values.length) + values.length) % values.length;
        reverse(values, 0, values.length - 1);
        reverse(values, 0, k - 1);
        reverse(values, k, values.length - 1);
    }
    public static void main(String[] args) {
        int[] values = {1, 2, 3, 4, 5};
        rotateRight(values, 2);
        for (int value : values) System.out.print(value + " ");
    }
}

How to approach the problem

Three reversals rotate in place: reverse everything, reverse the prefix that belongs at the front, then reverse the remaining suffix. Normalizing k makes rotations larger than the length and negative rotations predictable.

Approach

  1. Return early for an empty array.
  2. Reduce k modulo the array length.
  3. Apply the three range reversals.

Time and space complexity

Time: O(n). Space: O(1).

Edge cases to test

  • k equal to the length leaves the array unchanged.
  • A negative k can mean a left rotation after normalization.

Common mistakes

  • Dividing by values.length before checking emptiness.
  • Allocating and copying a second array when in-place behavior is requested.

Follow-up challenge

Rotate a linked list and compare why its pointer operations differ from arrays.

Related Arrays exercises

Practice all Arrays exercises · Run this idea in the Java compiler