Rotate Array in Java: 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

Related Arrays exercises

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