Arrays & Hashing · Pattern 4 of 26
The double reversal trick
Reverse the whole thing, then reverse each part. Rotating an array by k or reversing the order of words becomes O(n) time and O(1) extra space.
Watch the lesson
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
When to use it
- Rotate an array or string by k in place
- Reverse the order of words but not the letters inside them
The template
void rotate(int[] nums, int k) { // rotate right by k, in place
int n = nums.length;
k %= n;
reverse(nums, 0, n - 1); // reverse everything
reverse(nums, 0, k - 1); // then the first k
reverse(nums, k, n - 1); // then the rest
}
void reverse(int[] a, int i, int j) {
while (i < j) { int t = a[i]; a[i++] = a[j]; a[j--] = t; }
} def rotate(nums, k): # rotate right by k, in place
n = len(nums)
k %= n
def reverse(i, j):
while i < j:
nums[i], nums[j] = nums[j], nums[i]
i, j = i + 1, j - 1
reverse(0, n - 1) # reverse everything
reverse(0, k - 1) # then the first k
reverse(k, n - 1) # then the rest void rotate(vector<int>& nums, int k) { // rotate right by k, in place
int n = nums.size();
k %= n;
reverse(nums.begin(), nums.end()); // reverse everything
reverse(nums.begin(), nums.begin() + k); // then the first k
reverse(nums.begin() + k, nums.end()); // then the rest
} function rotate(nums, k) { // rotate right by k, in place
const n = nums.length;
k %= n;
const reverse = (i, j) => { while (i < j) { [nums[i], nums[j]] = [nums[j], nums[i]]; i++; j--; } };
reverse(0, n - 1); // reverse everything
reverse(0, k - 1); // then the first k
reverse(k, n - 1); // then the rest
} The variations
-
1Rotate by reversing three times
Right rotation by k: reverse all, reverse the first k, reverse the rest. Each element moves once per reversal.
-
2Reverse the words
Reverse the whole string, then reverse each word back. Clean up repeated spaces with a write pointer.
Mistakes to avoid
- Forgetting
k %= n: k can be larger than the array. - Reversing the parts in the wrong order for a left rotation (reverse the parts first, then the whole).
Lesson done
Next: Two pointers →Mark it done once you can write the template from memory and you have solved the worked examples yourself.