Reverse and rotate in place
25 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)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
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)); }}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]), leavinga[0]anda[5]untouched.- On odd-length array
b, whenleftandrightboth reach the middle index2,left < right(2 < 2) isfalse, so the middle element30stays in place.
- 3-line swap:
int temp = a[i]; a[i] = a[j]; a[j] = temp;(always readable and works even wheni == j). - Full array reversal: call
reverseRange(nums, 0, nums.length - 1). - Subarray reversal: call
reverseRange(nums, L, R)to reverse only indicesL..Rwhile 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
- k
- 3
Example 2 · Brute force: rotate by one position, k times (O(n × k) time, O(1) space)
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)); }}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)
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))); }}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)
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 }}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 = 3reduces 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
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)); }}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
kis a multiple ofn(15 % 5 == 0), the array does not need to move at all.
- Guard against
nums.length <= 1. - Reduce
k = k % nums.lengthso k lies in0 .. n - 1. - For right rotation by k:
reverse(0, n - 1), thenreverse(0, k - 1), thenreverse(k, n - 1). - For left rotation by k:
reverse(0, k - 1), thenreverse(k, n - 1), thenreverse(0, n - 1)(or right-rotate byn - 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]intoout[(i + k) % n]. Fast, but uses O(n) extra memory. - Three reversals (O(n) time, O(1) space):
- Reverse the entire array
0 .. n - 1:[1, 2, 3, 4, 5, 6, 7]→[7, 6, 5, 4, 3, 2, 1]. - Reverse the first k elements
0 .. k - 1:[7, 6, 5, ...]→[5, 6, 7, 4, 3, 2, 1]. - 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.
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); }}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!
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