Given a string containing words separated by spaces, reverse the order of the words. The words themselves should not be modified, only their positions swapped.
Split the string by spaces, reverse the resulting array, and join back with spaces. This is a classic string manipulation pattern that tests your ability to work with arrays derived from strings.
Time complexity is O(n) where n is the string length. Space complexity is O(n) for the word array and result. The split-reverse-join pattern is fundamental to string processing.
Edge cases include empty strings, single-word strings (no change), and strings with multiple spaces between words (preserved).
Example Input & Output
Empty string
Reverse word order
Three words reversed
Three words
Single word unchanged
Algorithm Flow

Solution Approach
Best Answers
class Solution {
public String solution(String s) {
String[] w=s.split(" ",-1);
StringBuilder r=new StringBuilder();
for(int i=w.length-1;i>=0;i--){r.append(w[i]);if(i>0)r.append(' ');}
return r.toString();
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
