Rotate an array to the right by k steps (e.g. [1,2,3,4,5], k=2 -> [4,5,1,2,3]).
The elegant O(1)-space trick is the reversal algorithm: reverse the whole array, then reverse the first k elements, then reverse the remaining n-k. Take k modulo n first so large k values wrap. O(n) time.
public static void rotate(int[] a, int k) {
int n = a.length; k %= n;
reverse(a, 0, n - 1);
reverse(a, 0, k - 1);
reverse(a, k, n - 1);
}
private static void reverse(int[] a, int i, int j) {
while (i < j) { int t = a[i]; a[i++] = a[j]; a[j--] = t; }
}function rotate(a, k) {
const n = a.length; k %= n;
const reverse = (i, j) => { while (i < j) { [a[i], a[j]] = [a[j], a[i]]; i++; j--; } };
reverse(0, n - 1); reverse(0, k - 1); reverse(k, n - 1);
return a;
}def rotate(a, k):
n = len(a)
k %= n
a[:] = a[-k:] + a[:-k] if k else a
return aRotation models circular buffers and round-robin scheduling; the reverse-thrice trick is a classic O(1)-space insight.
For k = 7 on a length-5 array, a candidate's code shifts out of bounds. Fix?