Rotate array by k
Rotate an array right by k positions in place using three reversals instead of a second array.
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.The idea
Rotating right by k moves the last k elements to the front. Reversing the whole array puts every element backward, including those two groups; reversing each group on its own then un-reverses it, leaving both groups internally correct and in the right place.
Code
public static void Rotate(int[] a, int k) {
k %= a.Length;
Reverse(a, 0, a.Length - 1);
Reverse(a, 0, k - 1);
Reverse(a, k, a.Length - 1);
}
static void Reverse(int[] a, int l, int r) {
while (l < r) { (a[l], a[r]) = (a[r], a[l]); l++; r--; }
}static void rotate(int[] a, int k) {
k %= a.length;
reverse(a, 0, a.length - 1);
reverse(a, 0, k - 1);
reverse(a, k, a.length - 1);
}
static void reverse(int[] a, int l, int r) {
while (l < r) { int t = a[l]; a[l] = a[r]; a[r] = t; l++; r--; }
}void reverseRange(vector<int>& a, int l, int r) {
while (l < r) { swap(a[l], a[r]); l++; r--; }
}
void rotate(vector<int>& a, int k) {
k %= (int)a.size();
reverseRange(a, 0, (int)a.size() - 1);
reverseRange(a, 0, k - 1);
reverseRange(a, k, (int)a.size() - 1);
}def rotate(a: list[int], k: int) -> None:
k %= len(a)
reverse(a, 0, len(a) - 1)
reverse(a, 0, k - 1)
reverse(a, k, len(a) - 1)
def reverse(a: list[int], l: int, r: int) -> None:
while l < r: a[l], a[r] = a[r], a[l]; l += 1; r -= 1Tips
- k %= a.Length first: rotating by the array length, or a multiple of it, changes nothing.
- Three reversals touch every element a constant number of times, so this beats the extra-array version on space without giving up O(n) time.
In the .NET library
The simplest correct version copies into a new array at (i + k) % n and copies back - O(n) space but easier to get right under pressure; reach for the reversal trick once that version is comfortable.