Rotate Array

Move the last k numbers of an array to the front, in place, with three reversals.

You are given an array of integers nums with at least one number, and a whole number k of zero or more. Rotate the array to the right by k steps. One step moves the last number to the front and every other number one place to the right. Change nums itself instead of returning a new array. k may be larger than the length of the array.

Example 1
Input: nums = [1, 2, 3, 4, 5, 6, 7], k = 3
Output: [5, 6, 7, 1, 2, 3, 4]
Example 2
Input: nums = [-1, -100, 3, 99], k = 2
Output: [3, 99, -1, -100]
Solution

The Idea

Picture seven people standing in a line, numbered 1 to 7. The last person walks round to the front, so 7 now stands first and everyone else is one place further back. That is one step of a rotation to the right. After three such steps the line reads 5, 6, 7, 1, 2, 3, 4, the output of Example 1.

Now look at what the three steps did overall. The last three people, 5, 6 and 7, are at the front, and the first four, 1 to 4, are at the back. Inside each of these two blocks the order has not changed. Example 2 works the same way: with k = 2, the last two numbers, 3 and 99, move in front of -1 and -100.

So a rotation swaps the two blocks. How do we do that without a second array to copy into? It is awkward, because the blocks have different sizes: 5, 6 and 7 must go where 1, 2 and 3 are, yet 1, 2, 3, 4 is four numbers long.

Reversing helps. Reverse the whole array and it reads 7, 6, 5, 4, 3, 2, 1. The last three numbers are already at the front, only backwards, and the first four are at the back, also backwards. Look at the picture below.

Rotating 1, 2, 3, 4, 5, 6, 7 right by 3 with three reversals. Reverse all gives 7, 6, 5, 4, 3, 2, 1. Reverse the first 3 gives 5, 6, 7, 4, 3, 2, 1. Reverse the last 4 gives 5, 6, 7, 1, 2, 3, 4.

The orange boxes are 5, 6 and 7, the numbers that must end up at the front. The green bracket under each row marks the part that was just reversed. In the row labelled "reverse all", reversing all seven numbers brings the orange block to the front as 7, 6, 5. In the row "reverse the first 3", it turns into 5, 6, 7. In the row "reverse the last 4", reversing those four turns 4, 3, 2, 1 into 1, 2, 3, 4, and the row is the answer.

So a rotation is three reversals: the whole array, then each of the two blocks. A reversal only swaps pairs of numbers inside the array, so it needs no second array.

Solution Approach

The simple ways to rotate are slow or need a second array. The three reversals avoid both, and leave three things to settle: what to do when k is larger than the array, how to reverse one block, and where the two blocks split.

The simple ways

What is the most direct way to rotate? Do exactly what the problem says: move the last number to the front, k times. Each step shifts all n numbers, where n is the length of the array, so this takes n × k moves. For 100,000 numbers and k = 50,000 that is 5 billion moves.

Another way copies the number at position i into a second array, at position (i + k) % n. The % operator gives the remainder of a division, so positions past the end wrap round to the start. In Example 1, counting positions from 0, the 5 at position 4 goes to (4 + 3) % 7 = 0. This takes only n moves, but it needs a second array as long as the first. The three reversals need neither the many moves nor the second array.

When k is larger than the array

What if k is 10 for seven numbers? After seven steps every number is back where it started, so ten steps give the same result as three. Only the remainder k % n matters. The code needs it too: the reversals use k as a position, and a k of n or more would point past the end of the array.

Reversing one block

How do we reverse only part of the array? Put one marker, lo, on the first position of the block and another, hi, on its last position. Swap the two numbers, move lo right and hi left, and stop when they meet or cross. This is the swap loop from Reverse String, used on a range. A block of one number, or an empty block such as the first block when k is 0, stops the loop before the first swap.

Where the two blocks split

After the full reversal, where does one block end and the other begin? The last k numbers now fill positions 0 to k - 1, and the other n - k numbers fill positions k to n - 1. Those are the ranges for the second and third reversal.

Java Solution

The method rotate works in these steps:

  1. First, store the length of the array in n and shrink k with k %= n, so k is less than n.
  2. Reverse the whole array with reverse(nums, 0, n - 1).
  3. Reverse the first block, positions 0 to k - 1, with reverse(nums, 0, k - 1).
  4. Reverse the second block, positions k to n - 1, with reverse(nums, k, n - 1). The method returns nothing, because it has changed nums itself.

The helper reverse gets the array as a and the block's first and last positions as lo and hi. While lo < hi, it swaps a[lo] and a[hi] through a temporary variable tmp, then moves lo right and hi left.

The main method rotates both examples, then [1, 2, 3] with k of 5, 3 and 0, and a one-number array with k = 7. A small method, show, prints each array before and after.

Java
import java.util.Arrays;

public class RotateArray {

    public static void rotate(int[] nums, int k) {
        int n = nums.length;
        k %= n;                               // rotating by n changes nothing
        reverse(nums, 0, n - 1);              // 1. reverse everything
        reverse(nums, 0, k - 1);              // 2. reverse the first k
        reverse(nums, k, n - 1);              // 3. reverse the rest
    }

    private static void reverse(int[] a, int lo, int hi) {
        while (lo < hi) {
            int tmp = a[lo];
            a[lo++] = a[hi];
            a[hi--] = tmp;
        }
    }

    private static void show(int[] nums, int k) {
        String before = Arrays.toString(nums);
        rotate(nums, k);
        System.out.println(before + ", k = " + k + " -> " + Arrays.toString(nums));
    }

    public static void main(String[] args) {
        show(new int[] {1, 2, 3, 4, 5, 6, 7}, 3);
        show(new int[] {-1, -100, 3, 99}, 2);
        show(new int[] {1, 2, 3}, 5);
        show(new int[] {1, 2, 3}, 3);
        show(new int[] {1, 2, 3}, 0);
        show(new int[] {42}, 7);
    }
}

Running it prints:

Output
[1, 2, 3, 4, 5, 6, 7], k = 3 -> [5, 6, 7, 1, 2, 3, 4]
[-1, -100, 3, 99], k = 2 -> [3, 99, -1, -100]
[1, 2, 3], k = 5 -> [2, 3, 1]
[1, 2, 3], k = 3 -> [1, 2, 3]
[1, 2, 3], k = 0 -> [1, 2, 3]
[42], k = 7 -> [42]

Example 1 ends as [5, 6, 7, 1, 2, 3, 4] and Example 2 as [3, 99, -1, -100], as expected. Look at the third line: [1, 2, 3] with k = 5 gives [2, 3, 1], the same as two steps, because 5 % 3 is 2.

The next two lines leave [1, 2, 3] as it was. With k = 3, k %= n makes k 0. With k at 0, the first block is the empty range 0 to -1, so the second reversal does nothing, and the third one undoes the first. On the last line, 7 % 1 is 0, and [42] stays [42].

Leaving out k %= n breaks the third line. For [1, 2, 3] and k = 5, the second reversal then gets the range 0 to 4. Its first swap reads position 4 of a three-number array and throws ArrayIndexOutOfBoundsException: Index 4 out of bounds for length 3.

The original implementation, RotateArray.java, is on GitHub.

Complexity

The work is three reversals, and each reversal is a series of swaps.

  • Time: O(n), for an array of n numbers, because the full reversal swaps about n / 2 pairs, and the two block reversals together swap about n / 2 more, so each number moves about twice.
  • Space: O(1). Each swap uses one temporary int, and no second array is created, unlike the copy into position (i + k) % n.