Problem
Reverse the order of words in a string. Words are separated by spaces. The returned string should contain a single space between words and no leading or trailing spaces.
Original: LeetCode 151: Reverse Words in a String.
Examples
Example 1
`s = "the sky is blue"``"blue is sky the"`Example 2
`s = " hello world "``"world hello"`Example 3
`s = "a good example"``"example good a"`Constraints
1 <= s.length <= 10^4scontains English letters (upper-case and lower-case), digits, and spaces' '.- There is at least one word in
s.
Hints
Hint 1
The input may have leading, trailing or repeated spaces. A word is a maximal sequence of non-space characters.
Hint 2
This is string cleanup plus a reverse of a sequence of tokens.
Solution
Tried it yourself? The approach, complexity, and code stay hidden until you choose.
Approach
Brute force. Split, filter, reverse, join. That is the straightforward linear solution.
Optimal. The split-and-join approach is already linear. An in-place version reverses the whole buffer, reverses each word, and compact-copies characters to remove extra spaces, which uses constant extra memory if the string is mutable.
Alternative. A stack of words, or two pointers that walk from the end and copy each word into a builder, also works.
Complexity
- Time
- O(n)
O(n) time and O(n) space for the tokens and the result.
- Space
- O(n)
Code
def reverse_words(s: str) -> str:
return " ".join(reversed(s.split()))
if __name__ == "__main__":
assert reverse_words("the sky is blue") == "blue is sky the"
assert reverse_words(" hello world ") == "world hello"
assert reverse_words("a good example") == "example good a"
print("ok")public class ReverseWordsInAString {
static String reverseWords(String s) {
var parts = s.trim().split("\s+");
var out = new StringBuilder();
for (int i = parts.length - 1; i >= 0; i--) {
out.append(parts[i]);
if (i > 0) out.append(' ');
}
return out.toString();
}
public static void main(String[] args) {
if (!reverseWords("the sky is blue").equals("blue is sky the")) throw new AssertionError();
if (!reverseWords(" hello world ").equals("world hello")) throw new AssertionError();
if (!reverseWords("a good example").equals("example good a")) throw new AssertionError();
System.out.println("ok");
}
}Edge cases
- Official samples: "the sky is blue" becomes "blue is sky the", " hello world " becomes "world hello", and "a good example" becomes "example good a".
trimplus a split on one-or-more whitespace is what removes the extra spaces.
Follow-ups
- Reverse Words in a String II asks you to do this in place on a character array.
- Reverse Words in a String III reverses the characters inside each word and leaves word order alone.
Interview script
"I split on whitespace so empty pieces disappear, reverse the list of words, and join with a single space. If they want constant extra space, I reverse the whole character buffer and then reverse each word in place."
Source: LeetCode 151: Reverse Words in a String Source: Java SE 17 API: String.split)
Sources (2)
- LeetCode 151: Reverse Words in a Stringleetcode.com
- Java SE 17 API: String.splitdocs.oracle.com