Reverse String

Reverse an array of characters in place by swapping pairs from both ends toward the middle.

A string is given as an array of characters s. Reverse it in place: change the array itself rather than building a new one, and use only a fixed amount of extra memory, however long the array is.

Example 1
Input: s = ["h", "e", "l", "l", "o"]
Output: ["o", "l", "l", "e", "h"]
Example 2
Input: s = ["H", "a", "n", "n", "a", "h"]
Output: ["h", "a", "n", "n", "a", "H"]
Solution

The Idea

Think of five letter tiles in a row on a table, spelling h, e, l, l, o. To make them read backwards, you could take them all off and lay them down again from the other end. That needs a second row of space, though, and the problem gives us only the one row.

So look at where each tile has to end up. The h at the front belongs at the back, and the o at the back belongs at the front. Those two simply trade places. The e in second place and the l in second-to-last place trade places too. Counting positions from 0, as Java does, the character at position i swaps with the one at position n - 1 - i, where n is the length of the array.

That raises the question of order and of when to stop. Look at the picture below. Two markers, lo on the left and hi on the right, point at the two characters that swap next.

Reversing h, e, l, l, o in place. At the start lo is at 0 and hi at 4, and h and o swap. After swap 1, lo is at 1 and hi at 3, and e and l swap. After swap 2, lo and hi both point at 2, the middle l, and the loop stops with o, l, l, e, h.

In the row labelled "start", lo is at 0 and hi at 4, so h and o swap. Both markers then take one step toward the middle. In the row labelled "after swap 1", they point at e and l, which swap next. In the row labelled "after swap 2", lo and hi both point at position 2, the middle l. It would only swap with itself, so the work is done, and the row reads o, l, l, e, h.

So reversing is a handful of swaps that work from the outside in, and it ends where the two markers meet. Two markers that start at opposite ends of an array and walk toward each other are usually called two pointers.

Solution Approach

Turning that idea into code means settling three things: how to swap two characters without losing one, when to stop, and why the easier ways that build a new string do not fit here.

Swapping two characters

How do we trade two characters inside one array? Writing s[hi] into s[lo] wipes out the character that was at lo. So that character is first copied into a spare variable, tmp, and written into s[hi] afterwards. One spare variable is all the extra memory the swap needs.

Where to stop

Why not simply run i over the whole array and swap s[i] with s[n - 1 - i]? The first half of that loop reverses the array, and the second half swaps every pair back. Run on h, e, l, l, o, it gives back h, e, l, l, o. The loop has to stop halfway, which is what the check lo < hi does.

With an odd length, the markers meet on the middle character, which stays where it is. With an even length, such as H, a, n, n, a, h, they cross after the swap of the two n's, and the check stops the loop just the same.

Building a new string instead

For a Java String, new StringBuilder(s).reverse() does the job in one line. It first copies the characters into a new buffer as long as the input, though, so its extra memory grows with the length. The same is true of copying the array backwards into a second array. Swapping inside s keeps the extra memory fixed, as the problem asks.

Java Solution

The method reverseString works in these steps:

  1. First, put the marker lo on position 0 and the marker hi on the last position, s.length - 1.
  2. Start a loop that runs while lo is less than hi.
  3. Inside the loop, copy s[lo] into tmp, write s[hi] into s[lo], and write tmp into s[hi].
  4. Move lo one step right and hi one step left, toward the middle.
  5. When the loop ends, the array is reversed. The method returns nothing, because it changed the caller's array.

The main method reverses both examples, a two-character array, a one-character array and an empty array, and prints each array before and after.

Java
import java.util.Arrays;

public class ReverseString {

    public static void reverseString(char[] s) {
        int lo = 0;
        int hi = s.length - 1;
        while (lo < hi) {
            char tmp = s[lo];      // keep the left character before it is overwritten
            s[lo] = s[hi];
            s[hi] = tmp;
            lo++;                  // both markers step toward the middle
            hi--;
        }
    }

    public static void main(String[] args) {
        char[][] inputs = {
            {'h', 'e', 'l', 'l', 'o'},
            {'H', 'a', 'n', 'n', 'a', 'h'},
            {'a', 'b'},
            {'x'},
            {}
        };
        for (char[] s : inputs) {
            String before = Arrays.toString(s);
            reverseString(s);
            System.out.println(before + " -> " + Arrays.toString(s));
        }
    }
}

Running it prints:

Output
[h, e, l, l, o] -> [o, l, l, e, h]
[H, a, n, n, a, h] -> [h, a, n, n, a, H]
[a, b] -> [b, a]
[x] -> [x]
[] -> []

The line for h, e, l, l, o matches the last row of the picture: two swaps, with the middle l left alone. In the line for H, a, n, n, a, h, the capital H moved from the front to the back, so case is kept as it is. [a, b] became [b, a] after a single swap.

The last two lines come back unchanged. For [x], hi starts at 0, the same as lo. For the empty array, hi starts at -1. In both cases lo < hi is false from the start, so the loop never runs and nothing is read out of range.

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

Complexity

The loop does one swap per pair of characters and then stops in the middle.

  • Time: O(n), because lo and hi each walk only half of the n characters, giving n / 2 swaps of three assignments each.
  • Space: O(1), because the only extra memory is lo, hi and tmp, the same for an array of five characters or five million.

The same swap loop, run on one part of an array at a time, reverses each word in Reverse Words in a String III.