Start learning free

LESSON 197 OF 410 · STRINGS

Reverse Words in a String in Java: split, reverse, join

Practice O(n) Read the full explanation

Given a string input, reverse the order of the words.

A word is defined as a sequence of non-space characters. The words in input will be separated by one space for simplicity.

Return a string of the words in reverse order concatenated by a single space.

Example:

Input:  input = "sky is blue"

Output:  "blue is sky"
STEP 1 OF 3
    Ctrl + Enter to check

    JAVA · STRINGS

    Reverse Words in Java, explained

    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

    1. Split and wrap. input.split(" ") produces the array of words. Passing it to Arrays.asList gives a List<String> view of that array, stored in words. The lesson declares it with var, so the compiler infers the type List<String>.
    2. Reverse in place. Collections.reverse(words) swaps elements from both ends toward the middle. It returns nothing: the list itself is changed.
    3. 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. Arrays and Collections live in java.util. In a file of your own, you need import java.util.*; at the top, otherwise the compiler reports that it cannot find the symbols. String.join needs no import.
    • Arrays.asList is a view, not a copy. The list is backed by the array that split returned. 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") or words.remove(0) throws an UnsupportedOperationException, because the list cannot grow or shrink. Swapping elements is allowed, so Collections.reverse works. If you need a list you can resize, wrap it: new ArrayList<>(Arrays.asList(...)).
    • split takes a regular expression. A single space has no special meaning in a regex, so split(" ") 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 reverse returns nothing. Writing return Collections.reverse(words); does not compile, because the method returns void. Call it on its own line, then use words.
    • 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.asList on an int[] gives a list with a single element, the whole array. It works as intended only for object arrays such as String[].

    Testing

    • "sky is blue" gives "blue is sky".
    • "hello" gives "hello".
    • "one two" gives "two one".
    • "" gives "".
    Keep going with JavaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free