Reverse Words in a String

Reverse the order of the words in a string, with exactly one space between them.

Given a string s, return its words in reverse order. A word is a run of characters that are not spaces. The result must have exactly one space between words and no spaces at the start or end, even if s has extra spaces.

Example 1
Input: s = "the sky is blue"
Output: "blue is sky the"
Example 2
Input: s = "  hello world  "
Output: "world hello"
Explanation: the spaces at the start and end are dropped.
Example 3
Input: s = "a good   example"
Output: "example good a"
Explanation: the three spaces between "good" and "example" become one.
Solution

The Idea

Read a sentence backwards, one word at a time, and "the sky is blue" becomes "blue is sky the". The words themselves stay as they are; only their order changes. If every gap were a single space, you could cut the string at each space and read the pieces from last to first.

Examples 2 and 3 are not that tidy. "  hello world  " has two spaces at each end, and "a good   example" has three spaces between "good" and "example". The answer keeps none of these extra spaces. So how do we pick out the words and pass over the spaces, however many there are?

Start from the end, because the last word of s is the first word of the answer. Walk left from the last character and step over any spaces. The first character that is not a space is the last letter of a word, so mark it with an index called end. Then keep walking left until you reach a space or go past the start of the string, and mark that spot with a second index, start. The word is everything after start, up to and including end. Look at the picture below, where each dot is a space.

The string two spaces, hello, a space, world, two spaces, with indices 0 to 14. In the first word row, end stops on d at index 12 and start on the space at 7, marking world. In the second word row, end stops on o at 6 and start on the space at 1, marking hello. The result so far becomes world hello.

In the row labelled "first word", end steps over the spaces at indices 14 and 13 and stops on d at index 12. start then walks left to the space at index 7, so the word is "world", indices 8 to 12. In the row labelled "second word", the walk goes on from that space: end stops on o at index 6, and start moves to the space at index 1, giving "hello". Left of index 1 there are only spaces, so the result so far, "world hello", is the answer.

So the words turn up in exactly the order the answer needs. The spaces of s are only stepped over, never copied, and the one space between two words is added by us. Two indexes that move through the same string like this are called two pointers. Here both move left, one after the other.

Solution Approach

Turning that idea into code means settling three things: whether to let the Java library split the string, how the two pointers find each word, and where the single spaces come from.

The library way

Can Java's String methods do this for us? Mostly, yes. s.trim() removes the spaces at both ends, and split("\\s+") cuts the rest at every run of whitespace, because the pattern "\\s+" means one or more whitespace characters. Reversing the pieces and joining them with one space gives the answer.

The pattern matters, though. With split(" "), every extra space leaves an empty piece behind, and joining puts those back as spaces: "a good   example" comes out as "example   good a". The library way also builds an array of all the words first. Scanning by hand needs no array and shows how the words are found.

Finding each word with two pointers

Where exactly does each word begin and end? end starts on the last index, s.length() - 1, and moves left while it sits on a space. If it drops below 0, only spaces were left and the scan is over. Otherwise start begins at end and moves left while it sits on a character that is not a space.

start stops on the space before the word, or at -1 when the word begins the string. The word is the characters from start + 1 to end. The next search goes on from start, so nothing to the right of it is read again.

One space between words

How do we get exactly one space between words and none at the ends? We add every space ourselves and never take one from s. Before a word is added to the result, check whether the result already holds a word. If it does, add one space first. The first word gets no space in front of it, and no word gets one after it, so both ends stay clean.

Java Solution

The method reverseWords works in these steps:

  1. First, create sb, a StringBuilder: a Java class that builds a string piece by piece without making a new string each time. Then set end to the last index, s.length() - 1.
  2. Run an outer loop while end >= 0. Inside it, a first inner loop moves end left past any spaces. If end drops below 0, break out of the outer loop, because only spaces were left.
  3. Set start to end, and a second inner loop moves start left until it reaches a space or -1.
  4. If sb already holds a word, append one space. Then append the word with sb.append(s, start + 1, end + 1), which copies the characters from index start + 1 up to, but not including, end + 1.
  5. Set end to start, so the next round of the outer loop carries on left of the word just copied.
  6. When the outer loop ends, return sb.toString().

The main method runs the three examples, a string of only spaces, and one word with spaces around it. Each result is printed between square brackets, so a leftover space at either end would show.

Java
public class ReverseWordsInString {

    public static String reverseWords(String s) {
        StringBuilder sb = new StringBuilder();
        int end = s.length() - 1;
        while (end >= 0) {
            while (end >= 0 && s.charAt(end) == ' ') {
                end--;                        // skip spaces after the word
            }
            if (end < 0) {
                break;                        // only spaces were left
            }
            int start = end;
            while (start >= 0 && s.charAt(start) != ' ') {
                start--;                      // move to the space before the word
            }
            if (sb.length() > 0) {
                sb.append(' ');               // one space between words
            }
            sb.append(s, start + 1, end + 1); // the word is s[start+1 .. end]
            end = start;
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println("[" + reverseWords("the sky is blue") + "]");
        System.out.println("[" + reverseWords("  hello world  ") + "]");
        System.out.println("[" + reverseWords("a good   example") + "]");
        System.out.println("[" + reverseWords("   ") + "]");
        System.out.println("[" + reverseWords("  single  ") + "]");
    }
}

Running it prints:

Output
[blue is sky the]
[world hello]
[example good a]
[]
[single]

Look at [world hello] and [example good a]: the brackets sit right against the words, so the spaces at the ends of "  hello world  " and the run of three spaces from Example 3 are gone. The fourth line, [], comes from "   ". The first inner loop moves end from 2 down to -1, the outer loop breaks before any word is found, and the method returns an empty string.

In the last line, [single], start stops on the space at index 1. sb is still empty at that point, so the word goes in without a space in front of it.

Complexity

The work is one walk from the right end of s to the left end, plus copying the words into sb.

  • Time: O(n), where n is the length of s. end and start only ever move left, so each of the n characters is checked at most twice, and each letter of a word is copied once.
  • Space: O(n) for the result. sb and the returned string hold at most n characters, and the two pointers are just two numbers.

To reverse the letters inside each word instead of the order of the words, see Reverse Words in a String III.