Problem overview
The method reverseWords receives a string input made of words separated by exactly one space. It returns a new string with the same words in the opposite order, again separated by single spaces. The words themselves are not changed: only their order is.
For "sky is blue" the result is "blue is sky". Note the difference from two other tasks people often mix this one up with. Reversing a whole sentence character by character would give "eulb si yks", and reversing each word in place would give "yks si eulb". Here every word stays readable and the sequence of words is flipped.
Approach: turn the sentence into a list of words
A String in Java is immutable and has no notion of words, so the first job is to get the words out. Calling split(" ") cuts the string at every space and returns a String[]. Because the statement guarantees exactly one space between words, this gives exactly the words, in their original order.
Once the words sit in a collection, reversing their order is a library call, and String.join glues them back together with a delimiter. The whole task becomes three operations: split, reverse, join. Each operation touches every word once, so the total work is proportional to the length of the string.
There is one wrinkle. Collections.reverse works on a List, not on an array. The method Arrays.asList bridges the gap by wrapping an array in a list without copying it.
A manual alternative is to loop over the array from the last index down to 0 and append each word to a StringBuilder, adding a space before every word except the first. It works and uses the same idea, but it needs more code and an index to get wrong. This lesson uses the library calls.
Step by step
- Split and wrap.
input.split(" ")produces the array of words. Passing it toArrays.asListgives aList<String>view of that array, stored inwords. The lesson declares it withvar, so the compiler infers the typeList<String>. - Reverse in place.
Collections.reverse(words)swaps elements from both ends toward the middle. It returns nothing: the list itself is changed. - Join and return.
String.join(" ", words)takes the delimiter first and the words second, and returns one string with the delimiter between consecutive words and none at the ends.
The solution in Java
class Solution {
public String reverseWords(String input) {
var words = Arrays.asList(input.split(" "));
Collections.reverse(words);
return String.join(" ", words);
}
}
A few Java details are worth a closer look:
- Imports.
ArraysandCollectionslive injava.util. In a file of your own, you needimport java.util.*;at the top, otherwise the compiler reports that it cannot find the symbols.String.joinneeds no import. Arrays.asListis a view, not a copy. The list is backed by the array thatsplitreturned. Reversing the list reverses that array too. Since the array is a temporary one, nobody notices here.- The list has a fixed size. Calling
words.add("x")orwords.remove(0)throws anUnsupportedOperationException, because the list cannot grow or shrink. Swapping elements is allowed, soCollections.reverseworks. If you need a list you can resize, wrap it:new ArrayList<>(Arrays.asList(...)). splittakes a regular expression. A single space has no special meaning in a regex, sosplit(" ")is safe. Characters such as.or|would need escaping.
Complexity
Time: O(n), where n is the length of the input. split scans the string once, reversing the list takes a number of swaps proportional to the word count, and join copies every character once.
Space: O(n). The array of words and the result string each hold about as many characters as the input. The reversal itself happens in place and needs only a couple of temporary variables.
Edge cases and common mistakes
- A single word.
"hello"splits into one element, reversing one element changes nothing, and the result is"hello". - The empty string.
"".split(" ")returns an array with one empty string, so the result is""and nothing crashes. - Extra spaces. The lesson promises single spaces, so its tests never include more. With input that breaks the promise,
split(" ")returns empty strings between consecutive spaces:"a b"gives[a, , b]. A leading space also produces an empty first element, while trailing spaces are silently dropped. For messy input, trim first and split on a pattern for one or more spaces:input.trim().split("\\s+"). - Forgetting that
reversereturns nothing. Writingreturn Collections.reverse(words);does not compile, because the method returnsvoid. Call it on its own line, then usewords. - Reversing characters instead of words.
new StringBuilder(input).reverse().toString()turns"sky is blue"into"eulb si yks". That reverses a string, not its words. - Passing a primitive array.
Arrays.asListon anint[]gives a list with a single element, the whole array. It works as intended only for object arrays such asString[].
Testing
"sky is blue"gives"blue is sky"."hello"gives"hello"."one two"gives"two one".""gives"".
