← Back to libraryQuestion 59 of 273
⌨️Java CodingIntermediate

Reverse the Words in a Sentence

📌 Definition:

Given "QA loves Java", return "Java loves QA" — reverse word order, not the characters.

📖 Detailed Explanation:

Split on whitespace, then join the tokens in reverse. Handle multiple/leading/trailing spaces by trimming and splitting on a whitespace regex (Python's split() does this by default). O(n).

💻 Solutions:
public static String reverseWords(String s) {
    String[] w = s.trim().split("\\s+");
    StringBuilder sb = new StringBuilder();
    for (int i = w.length - 1; i >= 0; i--) {
        sb.append(w[i]);
        if (i > 0) sb.append(' ');
    }
    return sb.toString();
}
function reverseWords(s) {
  return s.trim().split(/\s+/).reverse().join(' ');
}
def reverse_words(s):
    return ' '.join(s.split()[::-1])
🔑 Key Points:
  • Trim and split on whitespace runs
  • Join tokens in reverse order
  • Decide: collapse or preserve extra spaces
  • Handle empty/whitespace-only input
🌍 Real-World Example:

Word-order handling shows up in parsing log lines and building readable messages — and probes whether you handle messy whitespace.

🎯 Scenario-Based Interview Question:

Your code returns a leading space for " hello world ". What went wrong?