easyString ProblemsJava

Reverse the Order of Words in a Sentence

Reverse the order of words in a sentence while keeping each word's letters in place.

Quick Answer

Split the sentence into words on whitespace, then join them back together in reverse order. Trim first and split on one-or-more spaces so extra gaps do not create empty words. Each word keeps its own letter order; only the sequence of words is reversed. This runs in O(n) time.

Problem Statement

Given a sentence, reverse the order of its words so the last word comes first and the first word comes last. Each word keeps its own letters in the original order — only the sequence of words changes.

For example, Java is fun becomes fun is Java. Collapse any extra spacing so the output words are separated by single spaces.

Input: A single string s representing a sentence.

Output: The sentence with its words in reverse order, single-spaced.

Examples

Example 1
Input:  "Java is fun"
Output: fun is Java

The three words are emitted in reverse order.

Example 2
Input:  "the sky is blue"
Output: blue is sky the

Word order reverses; each word's spelling is unchanged.

Constraints

  • 0 <= s.length <= 10^5
  • Words are separated by one or more spaces

Think Before You Code

Reveal the questions to ask yourself first
  • How do you break a sentence into its individual words?
  • How do you handle runs of multiple spaces between words?
  • In what order do you re-join the words?
  • How do you avoid a trailing space in the output?

Hints

Open them one at a time — try after each before revealing the next.

Hint 1
Splitting on whitespace turns the sentence into an array of words.
Hint 2
Trim the input and split on \s+ so extra spaces do not produce empty words.
Hint 3
Walk the word array from the last index to the first, joining with single spaces.

Approach

Reveal the step-by-step approach

Split the sentence, then rebuild it backward.

  1. trim() the sentence and split("\\s+") to get an array of words with no empty entries from extra spacing.
  2. Create a StringBuilder.
  3. Loop from the last word index down to 0, appending each word.
  4. Append a single space between words but not after the last one.
  5. Return the builder's contents.

Reversing the traversal order of the array reverses the sentence while each word string stays exactly as it was.

Dry Run

Walk through the example step by step

Reversing the words of "Java is fun":

after trim + split: ["Java", "is", "fun"]

i | words[i] | result so far
--+----------+--------------
2 | fun      | "fun"
1 | is       | "fun is"
0 | Java     | "fun is Java"
final: "fun is Java"

Solution

Reveal the full Java solution
public class ReverseWords {
    public static String reverseWords(String s) {
        String[] words = s.trim().split("\\s+");
        StringBuilder sb = new StringBuilder();
        for (int i = words.length - 1; i >= 0; i--) {
            sb.append(words[i]);
            if (i > 0) {
                sb.append(" ");
            }
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(reverseWords("Java is fun"));     // fun is Java
        System.out.println(reverseWords("the sky is blue")); // blue is sky the
    }
}

Trimming and splitting on \\s+ produces a clean array of words, ignoring leading, trailing and repeated spaces. Iterating the array from the last index to the first emits the words in reverse order, and the i > 0 guard places a single space only between words, avoiding a trailing space. Each word is copied whole, so its letters are never rearranged.

Time: O(n) where n is the string lengthSpace: O(n) for the word array and output

Common Mistakes

  • Splitting on a single space so double spaces create empty words.
  • Leaving a trailing space by always appending a separator after each word.
  • Reversing the characters of the whole string instead of the word order.

Edge Cases to Test

  • A single-word sentence returns that word unchanged.
  • Leading and trailing spaces are trimmed away in the result.
  • An empty or all-space string returns an empty string.

Interview Follow-Ups

  • How would you reverse the word order in place using a char array?
  • How would you preserve the original spacing exactly instead of collapsing it?
  • How would you reverse the words without using split()?

Practising for Java interviews?

CodeBegun's Java Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.

Explore the Java Full Stack program →
Chat with us