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
- k % length handles k > length
- Reverse entire array, then reverse parts
- Or use extra array for simpler solution
Related Arrays exercises
- Practice Second Largest Element in Java
- Practice Remove Duplicates in Java
- Practice Merge Sorted Arrays in Java
Practice all Arrays exercises · Run this idea in the Java compiler