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.

2 variations · 2 problems · 2 with animated walkthroughs

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

Double Reversal Trick
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; }
}

The variations

  1. 1Rotate by reversing three times

    Right rotation by k: reverse all, reverse the first k, reverse the rest. Each element moves once per reversal.

  2. 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).
Next: Two pointers →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.