Reverse Words in a String

Reverse the order of words in a string (trim leading/trailing spaces, single space between words).

Example 1
Input: s="the sky is blue" → Output: "blue is sky the"
Example 2
Input: s=" hello world " → Output: "world hello"

Solution Approach

Split by whitespace, filter empty, reverse array, join with single space.

  • Split string by spaces
  • Filter out empty tokens
  • Reverse the array
  • Join with single space
Java
public String reverseWords(String s) {
    String[] words = s.trim().split("\s+");
    int left = 0, right = words.length - 1;
    while (left < right) {
        String tmp = words[left]; words[left] = words[right]; words[right] = tmp;
        left++; right--;
    }
    return String.join(" ", words);
}
  • Time Complexity: O(n)
  • Space Complexity: O(n)