MediumPythonJavaScriptTypeScript
Strings — Reverse Words in a String
AlgorithmsStringsTwo Pointers
solve(s) — a word is a run of non-space characters. Return the words of s in
reverse order, joined by a single space, with no leading or trailing spaces. The
input may contain leading, trailing or repeated spaces, which must not appear in the
output. A string with no words returns "".
The interview follow-up is to do it in place on a character array: reverse the whole
string, then reverse each word back. Here, any correct approach is accepted — but be able to
explain both.
Examples
solve("the sky is blue") → "blue is sky the"
solve(" hello world ") → "world hello"
solve("a good example") → "example good a"Sample tests
Test #1Plain sentence
Input: ["the sky is blue"]
Output: "blue is sky the"
Test #2Leading and trailing spaces
Input: [" hello world "]
Output: "world hello"
Test #3Repeated spaces
Input: ["a good example"]
Output: "example good a"