Video in progress
Rotate an array to the right by k steps, without allocating another array.
With three reversals: the whole array, then the first k elements, then the rest. First I do k %= n, because k can be larger than the array length. O(n) time, O(1) memory.
📖 Answer
[1,2,3,4,5,6,7], k = 3 → [5,6,7,1,2,3,4].
static void rotate(int[] a, int k) {
int n = a.length;
if (n == 0) return;
k %= n;
reverse(a, 0, n - 1); // [7,6,5,4,3,2,1]
reverse(a, 0, k - 1); // [5,6,7,4,3,2,1]
reverse(a, k, n - 1); // [5,6,7,1,2,3,4]
}
static void reverse(int[] a, int i, int j) {
while (i < j) {
int t = a[i]; a[i++] = a[j]; a[j--] = t;
}
}
Why does it work? When you reverse the whole array, the last k elements come to the front, only with their internal order flipped. The next two reversals restore the order inside each piece.
Typical mistakes: forgetting k %= n (with k = 10 and n = 7 the index goes out of bounds) and dividing by zero on an empty array, hence the n == 0 check.
A simpler solution is to allocate an int[] copy and do copy[(i + k) % n] = a[i]. It takes O(n) memory, but the code is easy to read. If there's no memory constraint, that's what I'd pick in production.
Sign up to mark studied questions and save your progress.