Reverse words in a string

Split on whitespace to get the words, reverse their order with two pointers, then rejoin with single spaces.

Time O(n)Space O(n)Code C#, Java, C++ and Python
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.

The idea

Splitting with RemoveEmptyEntries throws away the extra spaces in one step, so leading, trailing and doubled spaces never need special-case code. What is left is an ordinary array reversal with two pointers.

Code

public static string ReverseWords(string s) {
    var words = s.Split(' ', StringSplitOptions.RemoveEmptyEntries);
    int l = 0, r = words.Length - 1;
    while (l < r) { (words[l], words[r]) = (words[r], words[l]); l++; r--; }
    return string.Join(' ', words);
}
static String reverseWords(String s) {
    String[] words = s.trim().split("\\s+");
    int l = 0, r = words.length - 1;
    while (l < r) { String t = words[l]; words[l] = words[r]; words[r] = t; l++; r--; }
    return String.join(" ", words);
}
string reverseWords(const string& s) {
    vector<string> words; istringstream in(s); string w; while (in >> w) words.push_back(w);
    int l = 0, r = (int)words.size() - 1;
    while (l < r) { swap(words[l], words[r]); l++; r--; }
    string out; for (size_t i = 0; i < words.size(); i++) out += (i ? " " : "") + words[i]; return out;
}
def reverse_words(s: str) -> str:
    words = s.split()
    l, r = 0, len(words) - 1
    while l < r: words[l], words[r] = words[r], words[l]; l += 1; r -= 1
    return " ".join(words)

Tips

In the .NET library

Array.Reverse(words) is the built-in for the middle step; writing it out with l and r makes the pointer movement visible.