Write a Java method that reverses the order of words in a sentence.
Trim the text, split on one or more spaces, then join the pieces from last to first with a single space. It takes O(n) time and O(n) space for the word array and result.
Explain it simply
" hello world from Java " should become "Java from world hello": extra spaces disappear and the word order flips.
Line by line
public static String reverseWords(String s) {
String[] words = s.trim().split("\\s+"); // split on runs of spaces
StringBuilder sb = new StringBuilder();
for (int i = words.length - 1; i >= 0; i--) {
sb.append(words[i]);
if (i > 0) sb.append(' '); // no trailing space
}
return sb.toString();
}
// reverseWords(" hello world from Java ") returns "Java from world hello"trim() removes outer spaces, and the regex \\s+ treats any run of whitespace as a single separator. The loop walks the array backwards and adds a space between words only.
Complexity
Time O(n), space O(n).
What to say in the interview
"I split on whitespace, iterate from the end, and use a StringBuilder to avoid repeated concatenation. For an empty or all-space input, split gives one empty string, so I would add a check if the question requires returning an empty result. If asked to do it in place, I would work on a char array: reverse the whole array, then reverse each word."
Common mistakes
- Splitting on a single space, which leaves empty strings when words are separated by several spaces.