Errata
-
The first diagram in the problem statement shows the rotation in other way round.
It is N = -1 rotation and N = 2 rotation (instead of N = 1 and N = -2). -
Hint button doesn’t work properly.
Leetcode link
Leetcode - rotate-array
Note the Leetcode problem doesn’t include negative k rotations.
Alternative solution
The provided solution is good, this is a similar approach (Same space & time complexity):
class rotateArray{
public static void rotate_array(List<Integer> arr, int k) {
k = k % arr.size();
reverse(arr, 0, arr.size());
if (k < 0) {
reverse(arr, arr.size() + k, arr.size());
reverse(arr, 0, arr.size() + k);
} else {
reverse(arr, 0, k);
reverse(arr, k, arr.size());
}
}
public static void reverse(List<Integer> nums, int start, int end) {
for (int i = start; i < start + (end - start) / 2; i++) {
int temp = nums.get(i);
int reverseIdx = end - 1 - (i - start);
nums.set(i, nums.get(reverseIdx));
nums.set(reverseIdx, temp);
}
}
}