Reverse Words in a String

Pattern: String parsing

medium

Walk from the right. Skip spaces, then read one word back to its start, and add it to the answer with a single space between words. Extra spaces disappear on their own.

The problem

Given a string of words separated by spaces, return the words in reverse order, joined by single spaces. The input may have spaces at the start or end, or several spaces between words; none of those appear in the answer. For example, "the sky is blue" gives "blue is sky the", and " hello world " gives "world hello".

The function name reverseWords matches LeetCode. Use the link above for the exact statement and limits.

Think first

  • If you read the string from the right, in which order do you meet the words?
  • How do you find the start and end of each word?
  • How do you make sure exactly one space separates words in the answer?

Hints

    Brute force, and why it fails

    Split on spaces, drop empty pieces, reverse the list and join: also O(n), and fine in most languages. The scan from the right shows exactly how the words are found, and uses no list of words.

    The key insight

    Words are runs of non-space characters. Finding them from the right produces them in the order the answer needs, and deciding where spaces go at append time removes every extra space.

    Dry run

    0 
    1 
    h2 
    e3 
    l4 
    l5 
    o6 
    7 
    w8 
    o9 
    r10 
    l11 
    d12 
    13 
    14i

    s = two spaces, hello, a space, world, two spaces. Start i at the last character.

    Step 1 of 4

    The plan

    out = empty builder, i = n - 1
    while i >= 0:
        while i >= 0 and s[i] == ' ': i = i - 1
        if i < 0: stop
        end = i
        while i >= 0 and s[i] != ' ': i = i - 1
        if out is not empty: append ' '
        append s[i + 1 .. end]
    return out
    

    Complexity

    Time
    O(n)
    Space
    O(n)

    Each character is passed once. The answer takes O(n).

    Edge cases

    • One word with spaces around it, as in " one ": "one".
    • One character: itself.
    • Many spaces between words: one space in the answer.
    I've built my logic, show the code

    Java

    class Solution {
        public String reverseWords(String s) {
            StringBuilder out = new StringBuilder();
            int i = s.length() - 1;
            while (i >= 0) {
                while (i >= 0 && s.charAt(i) == ' ') i--;      // skip spaces
                if (i < 0) break;
                int end = i;
                while (i >= 0 && s.charAt(i) != ' ') i--;      // walk back over one word
                if (out.length() > 0) out.append(' ');
                out.append(s, i + 1, end + 1);
            }
            return out.toString();
        }
    }

    C++

    class Solution {
    public:
        string reverseWords(string s) {
            string out;
            int i = static_cast<int>(s.size()) - 1;
            while (i >= 0) {
                while (i >= 0 && s[i] == ' ') i--;           // skip spaces
                if (i < 0) break;
                int end = i;
                while (i >= 0 && s[i] != ' ') i--;           // walk back over one word
                if (!out.empty()) out += ' ';
                out += s.substr(i + 1, end - i);
            }
            return out;
        }
    };

    Python

    class Solution:
        def reverseWords(self, s: str) -> str:
            words, i = [], len(s) - 1
            while i >= 0:
                while i >= 0 and s[i] == " ":
                    i -= 1                           # skip spaces
                if i < 0:
                    break
                end = i
                while i >= 0 and s[i] != " ":
                    i -= 1                           # walk back over one word
                words.append(s[i + 1:end + 1])
            return " ".join(words)

    Common mistakes

    • Splitting on a single space, which leaves empty words when spaces repeat.
    • Reversing the characters of each word too.
    • Leaving a trailing space at the end of the answer.

    Similar problems