Skip to lesson

Reverse and rotate in place

Allocating a second array to reverse or rotate elements wastes O(n) extra memory. With a three-line swap helper and a range-reversal loop, you can reverse and rotate any array in place using O(1) extra space.

Swapping with a temp variable and reversing a range

An in-place algorithm changes the input data directly using only a few extra variables, so its extra space is O(1).

An in-place algorithm modifies the input array directly using only a few scalar variables (O(1) auxiliary space). The fundamental move of in-place array work is swapping two elements nums[i] and nums[j] using a temporary variable int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp;.

Example 1 · Reversing a specific subarray range versus the entire array in place

ReverseRangeDemo.javaJava
import java.util.Arrays;
public class ReverseRangeDemo {    static void reverseRange(int[] nums, int left, int right) {        while (left < right) {            int temp = nums[left];            nums[left] = nums[right];            nums[right] = temp;            left++;            right--;        }    }
    public static void main(String[] args) {        int[] a = {10, 20, 30, 40, 50, 60};        reverseRange(a, 1, 4); // Reverse only indices 1..4 ([20, 30, 40, 50])        System.out.println("After reverseRange(1, 4) : " + Arrays.toString(a));
        int[] b = {10, 20, 30, 40, 50};        reverseRange(b, 0, b.length - 1); // Reverse the full array        System.out.println("After full reverse       : " + Arrays.toString(b));    }}
Output
After reverseRange(1, 4) : [10, 50, 40, 30, 20, 60]
After full reverse       : [50, 40, 30, 20, 10]

What this code does

  • reverseRange(a, 1, 4) swaps (a[1], a[4]) and (a[2], a[3]), leaving a[0] and a[5] untouched.
  • On odd-length array b, when left and right both reach the middle index 2, left < right (2 < 2) is false, so the middle element 30 stays in place.
  • 3-line swap: int temp = a[i]; a[i] = a[j]; a[j] = temp; (always readable and works even when i == j).
  • Full array reversal: call reverseRange(nums, 0, nums.length - 1).
  • Subarray reversal: call reverseRange(nums, L, R) to reverse only indices L..R while leaving the rest untouched.

To reverse a range nums[left .. right] inclusive, place one index at left and another at right. While left < right, swap nums[left] and nums[right], then step inward with left++ and right--. Why while (left < right) and not i < n? If you swap nums[i] with nums[n - 1 - i] across the entire array (i = 0 to n - 1), you swap every pair twice and end up with the original un-reversed array! Stopping when left >= right swaps each mirror pair exactly once in ⌊ m / 2 ⌋ steps (O(m) time for range length m).

Rotating by k with three reversals: brute force versus O(n) in-place

Right rotation by k shifts every element k steps to the right, wrapping the last k elements around to the front. For example, rotating [1, 2, 3, 4, 5, 6, 7] right by k = 3 produces [5, 6, 7, 1, 2, 3, 4].

Rotate right by k = 3 with three reversals

Step 1 of 4

Array: 1, 2, 3, 4, 5, 6, 7.
k
3
We want [5, 6, 7, 1, 2, 3, 4]: the last 3 elements move to the front.

Example 2 · Brute force: rotate by one position, k times (O(n × k) time, O(1) space)

RotateOneByOneDemo.javaJava
import java.util.Arrays;
public class RotateOneByOneDemo {    static void rotateRight(int[] nums, int k) {        int n = nums.length;        if (n <= 1) return;        k = k % n;        for (int step = 0; step < k; step++) {            int last = nums[n - 1];            for (int i = n - 1; i > 0; i--) {                nums[i] = nums[i - 1];            }            nums[0] = last;        }    }
    public static void main(String[] args) {        int[] nums = {1, 2, 3, 4, 5, 6, 7};        rotateRight(nums, 3);        System.out.println("Rotate right by 3 : " + Arrays.toString(nums));    }}
Output
Rotate right by 3 : [5, 6, 7, 1, 2, 3, 4]

What this code does

  • Each pass moves the last element to the front and shifts everything else one place right.
  • k passes of n shifts each cost O(n × k) time, but no extra array is needed.

Example 3 · Better: copy into a new array at the shifted index (O(n) time, O(n) space)

RotateCopyDemo.javaJava
import java.util.Arrays;
public class RotateCopyDemo {    static int[] rotateRight(int[] nums, int k) {        int n = nums.length;        int[] result = new int[n];        for (int i = 0; i < n; i++) {            result[(i + k) % n] = nums[i];        }        return result;    }
    public static void main(String[] args) {        int[] nums = {1, 2, 3, 4, 5, 6, 7};        System.out.println("Rotate right by 3 : " + Arrays.toString(rotateRight(nums, 3)));    }}
Output
Rotate right by 3 : [5, 6, 7, 1, 2, 3, 4]

What this code does

  • Every element is placed straight into its final index (i + k) % n, so the array is read once.
  • This is faster than shifting k times, but the new array costs O(n) extra space.

Example 4 · Optimal: three reversals, including k >= n (O(n) time, O(1) space)

RotateRightThreeReversalsDemo.javaJava
import java.util.Arrays;
public class RotateRightThreeReversalsDemo {    static void reverse(int[] nums, int l, int r) {        while (l < r) {            int tmp = nums[l];            nums[l++] = nums[r];            nums[r--] = tmp;        }    }
    static void rotateRightWithTrace(int[] nums, int k) {        int n = nums.length;        if (n <= 1) return;        k = k % n;        System.out.println("Start (k reduced to " + k + ") : " + Arrays.toString(nums));        reverse(nums, 0, n - 1);        System.out.println("1. Reverse all [0.." + (n - 1) + "]   : " + Arrays.toString(nums));        reverse(nums, 0, k - 1);        System.out.println("2. Reverse [0.." + (k - 1) + "]       : " + Arrays.toString(nums));        reverse(nums, k, n - 1);        System.out.println("3. Reverse [" + k + ".." + (n - 1) + "]       : " + Arrays.toString(nums));    }
    public static void main(String[] args) {        int[] nums = {1, 2, 3, 4, 5, 6, 7};        rotateRightWithTrace(nums, 10); // k = 10 -> 10 % 7 = 3    }}
Output
Start (k reduced to 3) : [1, 2, 3, 4, 5, 6, 7]
1. Reverse all [0..6]   : [7, 6, 5, 4, 3, 2, 1]
2. Reverse [0..2]       : [5, 6, 7, 4, 3, 2, 1]
3. Reverse [3..6]       : [5, 6, 7, 1, 2, 3, 4]

What this code does

  • First k = 10 % 7 = 3 reduces 10 right shifts to 3 right shifts.
  • Reversing the whole array brings the last 3 elements (5, 6, 7) to the front in reverse order (7, 6, 5); reversing [0..2] and [3..6] restores the internal order of both halves.
  • It is faster than shifting by one and needs no extra array, because reversing swaps elements inside the same array.

Example 5 · Left rotation by k using three reversals

RotateLeftDemo.javaJava
import java.util.Arrays;
public class RotateLeftDemo {    static void reverse(int[] nums, int l, int r) {        while (l < r) {            int tmp = nums[l];            nums[l++] = nums[r];            nums[r--] = tmp;        }    }
    static void rotateLeft(int[] nums, int k) {        int n = nums.length;        if (n <= 1) return;        k = k % n;        if (k == 0) return;        reverse(nums, 0, k - 1);        reverse(nums, k, n - 1);        reverse(nums, 0, n - 1);    }
    public static void main(String[] args) {        int[] a = {10, 20, 30, 40, 50};        rotateLeft(a, 2);        System.out.println("Left rotate by 2  : " + Arrays.toString(a));
        int[] b = {10, 20, 30, 40, 50};        rotateLeft(b, 15); // 15 % 5 == 0        System.out.println("Left rotate by 15 : " + Arrays.toString(b));    }}
Output
Left rotate by 2  : [30, 40, 50, 10, 20]
Left rotate by 15 : [10, 20, 30, 40, 50]

What this code does

  • For left rotation by k, we reverse the first k elements [0..k-1], reverse the remaining [k..n-1], and finally reverse the whole array [0..n-1].
  • When k is a multiple of n (15 % 5 == 0), the array does not need to move at all.
  1. Guard against nums.length <= 1.
  2. Reduce k = k % nums.length so k lies in 0 .. n - 1.
  3. For right rotation by k: reverse(0, n - 1), then reverse(0, k - 1), then reverse(k, n - 1).
  4. For left rotation by k: reverse(0, k - 1), then reverse(k, n - 1), then reverse(0, n - 1) (or right-rotate by n - k).
  • Brute force (O(n · k) time, O(1) space): Rotate right by 1 step (O(n) shift) and repeat k times. When n = 10⁵ and k = 50,000, this performs 5 × 10⁹ shifts and times out.
  • Extra array (O(n) time, O(n) space): Copy nums[i] into out[(i + k) % n]. Fast, but uses O(n) extra memory.
  • Three reversals (O(n) time, O(1) space):
  1. Reverse the entire array 0 .. n - 1: [1, 2, 3, 4, 5, 6, 7] → [7, 6, 5, 4, 3, 2, 1].
  2. Reverse the first k elements 0 .. k - 1: [7, 6, 5, ...] → [5, 6, 7, 4, 3, 2, 1].
  3. Reverse the remaining n - k elements k .. n - 1: [..., 4, 3, 2, 1] → [5, 6, 7, 1, 2, 3, 4]. Each element is swapped at most twice (once in the full reversal and once in its half), so the total work is O(n) time and O(1) extra space!

Order of execution

Rotate right with reversals

Tap the steps of a right rotation by k, in the order they happen.

When k is larger than n (or zero)

Rotating an array of length n by n steps brings every element right back to its starting index. Therefore, rotating by k steps has the exact same final state as rotating by k % n steps.

ReduceK.javaJava
public class ReduceK {    public static void main(String[] args) {        int[] nums = {1, 2, 3, 4, 5};        int k = 12;        if (nums.length > 0) {            k = k % nums.length; // 12 % 5 = 2        }        System.out.println("rotate right by " + k);    }}
Output
rotate right by 2

For example, if n = 5 and k = 12, 12 % 5 = 2, so rotating right 12 times is identical to rotating right 2 times. If you forget k = k % n before calling reverseRange(nums, 0, k - 1), any test case with k > n throws an immediate ArrayIndexOutOfBoundsException at index k - 1!

Always reduce k = k % nums.length (after checking nums.length > 0) as the very first line of any array rotation method.

Next step

Check your understanding

10 quick questions