Reverse Words in a String III

Turn the letters of every word around while the words keep their places, by swapping each word's letters from both ends.

Given a string s made of words separated by single spaces, reverse the letters inside every word, but keep the words in their original order. The string has no spaces at its start or end. Return the new string.

Example 1
Input: s = "Let's take a coding contest"
Output: "s'teL ekat a gnidoc tsetnoc"
Example 2
Input: s = "Mr Ding"
Output: "rM gniD"
Solution

The Idea

Read the words "Mr Ding" backwards, one word at a time. "Mr" reads "rM" and "Ding" reads "gniD", but "Mr" still comes first and the space stays between them. That is exactly the answer to Example 2: only the letters inside each word turn around.

Example 1 works the same way. "take" becomes "ekat", and the one-letter word "a" stays "a", because a single letter reads the same both ways. The apostrophe in "Let's" is just another character, so "Let's" becomes "s'teL".

A program does not see words, though. It sees one row of characters, numbered from 0. So two questions come up: how does it know where one word ends and the next begins, and how does it turn one word around inside that row? Look at the picture below.

The string Mr Ding at indexes 0 to 6. The space at 2 and the end of the string at 7 mark the words 0 to 1 and 3 to 6. Mr has already become rM. To reverse Ding, lo at 3 and hi at 6 swap D and g, then move inward and swap i and n. The result is rM gniD.

The row labelled "before" shows "Mr Ding" at indexes 0 to 6. The space at index 2 closes the first word, which runs from 0 to 1. The second word has no space after it, but the string ends at index 7, and that closes it just the same. So a word is everything between two boundaries, and a boundary is either a space or the end of the string.

Once a word's two ends are known, turning it around takes a few swaps. The row labelled "reversing Ding" starts with one marker, lo, on the word's first letter and another, hi, on its last. The 1st swap exchanges D and g. Then both markers step toward the middle, and the 2nd swap exchanges i and n. The markers have now met, and the row labelled "after" reads "rM gniD".

Using two markers that start at the two ends and walk toward each other is called the two-pointer technique. Here it runs once for every word, and each run only touches the letters between that word's two boundaries.

Solution Approach

The code needs answers to four questions: where the letters can be changed, how to find each word's boundaries, what to do with the last word, and how to reverse one word.

Changing letters in a Java string

Can we swap letters inside s directly? No: a Java String cannot be changed once it is made. So the solution copies the letters into a char array, c, with s.toCharArray(). It swaps letters inside c and, at the end, builds the answer from it with new String(c).

Finding each word's boundaries

How does the code find where a word starts and ends? It keeps start on the first letter of the current word and moves a second index, end, forward one character at a time. When end reaches a space, the word runs from start to end - 1. The next word begins just after the space, at end + 1.

Handling the last word

What about the last word, which has no space after it? The loop that moves end lets it go one step past the last character, to c.length, and treats that position like a space. In the picture, that is index 7, labelled "end of string". The check end == c.length comes first, so c[end] is never read at that position.

That one extra step past the end matters. A loop that stops at end < c.length never sees a boundary after the last word. Run on "Mr Ding", that version returns "rM Ding", with "Ding" left as it was.

Reversing one word

How does one word get turned around? A small helper, reverse, takes the word's first index as lo and its last as hi. While lo is left of hi, it swaps the two letters and moves both markers one step inward. In a word with an odd number of letters, the markers meet on the middle letter, which stays where it is. A one-letter word starts with the markers already together, so nothing is swapped.

A shorter version with split

As an alternative, Java can do the cutting and reversing for us. s.split(" ") cuts the string into an array of words, new StringBuilder(word).reverse() turns each word around, and String.join(" ", words) glues them back with spaces. It gives the same answers on both examples, and its time also grows in step with the length of the string. But it creates a new string for every word, while the array version works in one array.

Java Solution

Here is what reverseWords does, in order:

  1. First, copy the string into a char array c with s.toCharArray(), so letters can be swapped.
  2. Set start to 0, the first letter of the first word.
  3. Move end with a for loop from 0 up to and including c.length. When end equals c.length or c[end] is a space, the current word is c[start .. end - 1].
  4. Reverse that word with reverse(c, start, end - 1). Inside the helper, lo and hi swap letters through a temporary tmp and move inward until they meet. Back in the loop, set start = end + 1, just after the space.
  5. When the loop is done, return new String(c).

The main method runs both examples, a single word, a sentence of one-letter words, and an empty string, and prints each answer in quotes so an empty answer is still visible.

Java
public class ReverseWordsInStringIII {

    public static String reverseWords(String s) {
        char[] c = s.toCharArray();
        int start = 0;
        for (int end = 0; end <= c.length; end++) {
            if (end == c.length || c[end] == ' ') {
                reverse(c, start, end - 1);   // the word is c[start .. end-1]
                start = end + 1;              // next word begins after the space
            }
        }
        return new String(c);
    }

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

    public static void main(String[] args) {
        System.out.println("\"" + reverseWords("Let's take a coding contest") + "\"");
        System.out.println("\"" + reverseWords("Mr Ding") + "\"");
        System.out.println("\"" + reverseWords("abc") + "\"");
        System.out.println("\"" + reverseWords("a b c") + "\"");
        System.out.println("\"" + reverseWords("") + "\"");
    }
}

Running it prints:

Output
"s'teL ekat a gnidoc tsetnoc"
"rM gniD"
"cba"
"a b c"
""

"Mr Ding" comes out as "rM gniD", the same as the row labelled "after" in the picture. Look at "cba" on the third line: "abc" has no space at all, so its only boundary is the end of the string, and that is enough to reverse it.

The fourth line, "a b c", is unchanged, because every word has one letter and reverse starts with lo equal to hi. For the empty string on the last line, the loop runs once with end at 0, which is c.length. It calls reverse(c, 0, -1), which swaps nothing, and returns "".

Complexity

The work is one pass of end over the string, plus the swaps inside each word.

  • Time: O(n), where n is the number of characters in s. end visits each character once, and since words never overlap, all the reverse calls together swap each letter at most once.
  • Space: O(n), because toCharArray() copies all n characters. A Java string cannot be changed in place, so the answer needs a new copy of that size anyway.

To reverse the order of the words instead of their letters, see Reverse Words in a String.